json是一种轻量级的数据交换格式,其形式很类似于python中的字典数据类型。日常对json数据文件的操作一般分为文本型与文件型,文本型即json字符串用json.loads()
,文件型用json.load()
,二者功能都是将json数据文件或字符串中的对象转为python对象,即转为python中对应的数据类型和结构。
import json
people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name": "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
]
}
'''
people_dict = json.loads(people_string)
print(people_dict)
转为python对象的结果:
{‘people’: [{‘name’: ‘John Smith’, ‘phone’: ‘615-555-7164’, ‘emails’: [‘johnsmith@bogusemail.com’, ‘john.smith@work-place.com’], ‘has_license’: False}, {‘name’: ‘Jane Doe’, ‘phone’: ‘560-555-5153’, ‘emails’: None, ‘has_license’: True}]}
import json
with open("population_data.json") as f:
data = json.load(f)
原json文件如上图所示,转为python对象后就可利用python的字典操作获取所需的键或者值。
我们也可以将python对象转为json字符串或者文件,转为字符串用json.dumps()
,转为文件用json.dump()
。
转为json文件
import json
with open("population_data.json") as f:
data = json.load(f)
with open("new_population_data.json", mode='w') as f:
json.dump(data, f)
转为json字符串
import json
people_string = '''
{
"people": [
{
"name": "John Smith",
"phone": "615-555-7164",
"emails": ["johnsmith@bogusemail.com", "john.smith@work-place.com"],
"has_license": false
},
{
"name": "Jane Doe",
"phone": "560-555-5153",
"emails": null,
"has_license": true
}
]
}
'''
people_dict = json.loads(people_string)
new_people_string = json.dumps(people_dict)