Python 3.7 json 的使用,json 編碼與解碼,json 轉字典,字典轉 json,正確設置 ensure_ascii 的值

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章