json读写

# 数据存储:json.dump()和json.load()
# date:2017-07-17
import json
 
file_name = 'D:/json_file.txt'
nums = [3, 4, 5, 7, 1, 9]
# nums = {"name": "Mike", "age": 12}
with open(file_name, 'w') as file_obj:
    '''写入json文件'''
    json.dump(nums, file_obj)
    print("写入json文件:", nums)
 
with open(file_name) as file_obj:
    '''读取json文件'''
    numbers = json.load(file_obj)  # 返回列表数据,也支持字典
    print("读取json文件:", numbers)
  

运行结果:

写入json文件: [3, 4, 5, 7, 1, 9]
读取json文件: [3, 4, 5, 7, 1, 9]

但是在读写中文时,存储的文本则可能会显示为乱码,这时,只要将代码进行如下改动即可

 json.dump(nums, file_obj,ensure_ascii=False)

 但是,保存的json文件可能会挤在一块,这样在看起来就会很乱了,所以呢,要使用indent

json.dump(nums, file_obj,indent=4,ensure_ascii=False)

这样再看保存好的json文件,就会觉得比之前要更清晰了

参考地址 

https://www.cnblogs.com/gongxr/p/7225476.html

https://www.cnblogs.com/veitch-623/p/7685880.html

https://blog.csdn.net/qq_30242609/article/details/57420777

posted on 2018-08-14 16:09  凌落成迷  阅读(1768)  评论(0编辑  收藏  举报