Python 中要使用 json,需要引用 json
模块。
字典转 json 字符串
import json
dictionary = {'code': 1, 'msg': '成功', 'data': [{'user': 'yao7778899', 'age': 28, 'sex': '男'}]}
json_str = json.dumps(dictionary, ensure_ascii=False) # ensure_ascii 默认值为 True,中文使用 ascii 编码,即中文被编码成 `\uXXXX`
print(json_str) # {"code": 1, "msg": "成功", "data": [{"user": "yao7778899", "age": 28, "sex": "男"}]}
json 字符串转字典
import json
json_str = '{"code": 1, "msg": "成功", "data": [{"user": "yao7778899", "age": 28, "sex": "男"}]}'
json_dict = json.loads(json_str)
print(json_dict) # {'code': 1, 'msg': '成功', 'data': [{'user': 'yao7778899', 'age': 28, 'sex': '男'}]}
code = json_dict['code']
user = json_dict['data'][0]['user']
age = json_dict['data'][0]['age']
print(code) # 1
print(user) # yao7778899
print(age) # 28