读取json

  1. import json
  2. json_file = 'test.json'
  3. with open(json_file,'r', encoding = 'utf-8') as load_f:
  4. data = json.load(load_f)
  5. print(data)

test.json

  1. {
  2. "user_name": "test1",
  3. "password" : "test2",
  4. "id" : "1234567",
  5. "file_list": ["f1", "f2","f3"]
  6. }

保存json

  1. 注意python3保存文件的时候默认Unicode,需要在dump的时候ensure_ascii=False才可以,不然保存的仍然是Unicode
  2. 使用intend = 4可以设置保存json文件的时候缩进。 ```python import json

dic = {“user_name”: “test1”, “password” : “test2”, “id” : “1234567”, “file_list”: [“f1”, “f2”,”f3”]}

filename=’test.json’

with open(filename,’w’, encoding = ‘utf-8’) as file_obj: json.dump(dic, file_obj, ensure_ascii=False) ```

参考链接