The json module provides a simple way to encode and decode JSON data.
1.json.dumps converts a python data structure into JSON:
# 导入json 模块
import json
data = {
'name':'myname',
'age':200,
}
# 使用json.dumps() 返回一个json
json_str = json.dumps(data)
2.json.loads 将一个JSON编码的字符串转换为一个python 数据结构
import json
json_str ={
"employees": [
{
"firstName": "Bill",
"lastName": "Gates"
},
{
"firstName": "George",
"lastName": "Bush"
},
]
}
data = json.loads(json_str)
3. json.dump() and json.load() to encode and decode JSON data for processing files.
with open('test.json', 'w') as f:
json.dump(data, f)
with open('test.json', 'r') as f:
data = json.load(f)