一.python2
1.序列化
1.1 将字典转化为字符串
json.dumps()
import json
dict_json = {'a': 123, 'b': 456, 'c': 'pen'}
print json.dumps(dict_json)
{"a": 123, "c": "pen", "b": 456}
1.2 将字典转为格式化后的字符串
json.dumps(dict, indent=2, separators=(',', ':'))
indent: 缩进位数
separators: 元素间以逗号分隔, key-value间以冒号分隔
import json
dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "hello"}, "c": 3}
format_json = json.dumps(dict_json, indent=4, separators=(',', ':'))
print format_json
{
"a":1,
"c":3,
"b":{
"list":[
1,
2,
3
],
"str":"hello"
}
}
1.3 将字典写进文件
json.dump(json_dict, file_object)
import json
json_dict = {"a": 123, "b": 456, "c": "pen"}
file_object = open('why.json', 'w')
json.dump(json_dict, file_object)
2.反序列化
2.1 将字符串转为字典
json.loads()
import json
dict_str = '{"a": 123, "b": 456, "c": "pen"}'
print json.loads(dict_str)
{u'a': 123, u'c': u'pen', u'b': 456}
2.2 读取文件中的数据并转为字典
json.load(file_object)
import json
file_object = open('why.json', 'r')
info = json.load(file_object)
print(info)
print type(info)
{u'a': 123, u'c': u'pen', u'b': 456}
<type 'dict'>
二.python3:
1.序列化
1.1 将字典转化为字符串
json.dumps(dict_json, ensure_ascii=False)
ensure_ascii=False 解决中文乱码
import json
dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}
format_json = json.dumps(dict_json, ensure_ascii=False)
print(format_json)
{"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}
1.2 将字典转为格式化后的字符串
json.dumps(dict_json, indent=4, separators=(',', ':'), ensure_ascii=False)
import json
dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}
format_json = json.dumps(dict_json, indent=4, separators=(',', ':'), ensure_ascii=False)
print(format_json)
{
"a":1,
"b":{
"list":[
1,
2,
3
],
"str":"测试"
},
"c":3
}
1.3 将字典写进文件
json.dump(json_dict, file_object, ensure_ascii=False)
import json
json_dict = {"a": 123, "b": 456, "c": "测试"}
file_object = open('why.json', 'w', encoding="utf8")
json.dump(json_dict, file_object, ensure_ascii=False)
2.反序列化
2.1 将字符串转为字典
json.loads(dict_str)
import json
dict_str = '{"a": 123, "b": 456, "c": "测试"}'
print(json.loads(dict_str))
{'a': 123, 'b': 456, 'c': '测试'}
2.2 读取文件中的数据并转为字典
json.load(file_object)
import json
file_object = open('why.json', 'r', encoding="utf8")
info = json.load(file_object)
print(info)
{'a': 123, 'b': 456, 'c': '测试'}