# 获取字典dict
In [1]: data = {i:ord(i) for i in list('abcde')}
In [2]: data
Out[2]: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}
In [3]: import json
# dict -> json
In [5]: json.dumps(data)
Out[5]: '{"a": 97, "b": 98, "c": 99, "d": 100, "e": 101}'
# json.dump(dict, filename),将dict格式的数据编码为json格式并存储
In [12]: with open('temp.json', 'w') as f:
...: json.dump(data, f)
...:
# json.load(filename),将读取的数据解码为dict格式
In [13]: with open('temp.json', 'r') as f:
...: new_data = json.load(f)
...:
In [14]: new_data
Out[14]: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}
In [17]: json_data = json.dumps(data)
In [18]: type(json_data)
Out[18]: str
In [19]: dict_data = json.loads(json_data)
In [21]: dict_data
Out[21]: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}
In [22]: dict_data.__class__
Out[22]: dict
In [23]: json_data.__class__
Out[23]: str
In [25]: with open('temp.json', 'r') as f:
...: temp = f.read()
...:
In [26]: temp
Out[26]: '{"a": 97, "b": 98, "c": 99, "d": 100, "e": 101}'
In [27]: json.loads(temp)
Out[27]: {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101}
小结:
json.load(file_obj)
,接收文件对象,将其解码并返回为字典格式的数据json.loads(json_str)
, 接收json
格式字符串,将其解码并返回字典格式的数据json.dump(dict, file_obj)
, 接收dict
格式数据,将其编码为json
格式的数据,最后写入文件中json.dumps(dict)
, 接收dict
格式数据,并返回json
格式的数据json.load、json.dump
处理文件的的读与写;json.loads、json.dumps
处理json
与dict
之间的解码和编码