Python基础

python对json的操作总结

2018-12-13  本文已影响0人  正经一米八
Json简介
Python对象编码为Json对象
python_dic1 = {'username': 'jiangnanmax', 'nickname': '江', 'major': 'CS'}
json_dic1 = json.dumps(python_dic1)
print(json_dic1)
json_dic2 = json.dumps(python_dic1, sort_keys=True, indent=4, separators=(',', ': '),
                           ensure_ascii=False)
print(json_dic2)

输出如下:
{"username": "jiangnanmax", "nickname": "\u6c5f", "major": "CS"}
{
    "major": "CS",
    "nickname": "江",
    "username": "jiangnanmax"
}
Json对象解码为Python对象
python_dic1 = {'username': 'jiangnanmax', 'nickname': '江', 'major': 'CS'}
json_dic1 = json.dumps(python_dic1, ensure_ascii=False)
print(json_dic1)
print(type(json_dic1))
输出:
{"username": "jiangnanmax", "nickname": "江", "major": "CS"}
<class 'str'>
    
python_dic2 = json.loads(json_dic1)
print(python_dic2)
print(type(python_dic2))
输出:
{'username': 'jiangnanmax', 'nickname': '江', 'major': 'CS'}
<class 'dict'>
    
python_dic2 = str(python_dic2) # 把dict类型转化为str类型
print(json.loads(python_dic2))
报错:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
上一篇下一篇

猜你喜欢

热点阅读