Python中的JSON数据处理
1.JSON
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,表示实体的属性关系。
- 以“
名称 : 值
”的格式存储; - 写入和读取都按照dict的类型,区别于csv文件的字符串类型;
- json本质上使用字符串类型进行存储,但是load方法可以在读取时自动解析出数据类型;
json
与dict
本质上时不同的,json是一种文件的组织方式,而dict是程序语言中定义的一种数据结构- python中的
True
和None
分别对应json中的true
和null
import json
python_John = {
'firstName':'John',
'lastName':'Smith',
'isAlive': True,
'age': 25,
'address':{
'streetAddress': '21 2nd Street',
'city': 'New York',
'state': 'NY',
'postalCode': '10021-3100'
},
'phoneNumbers':[
{
'type': 'Home',
'number': '646 555-4567'
},
{
'type': 'Mobile',
'number': '123 679-4567'
}
],
'children': [],
'spouse': None
}
js_John = json.dumps(python_John)
# 查看js_John
Out[21]: '{"firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": {"streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100"}, "phoneNumbers": [{"type": "Home", "number": "646 555-4567"}, {"type": "Mobile", "number": "123 679-4567"}], "children": [], "spouse": null}'
2.四个方法:序列化与反序列化
2.1 序列化 dump()与dumps()
dump(obj,fp)
:可以直接将python数据转化为json格式并存储到指定路径文件中;
dumps(obj)
:将python数据转化为字符串格式的json数据,除了没有指定存储路径外,各参数与dump()相同。
上述例子中使用的是dumps(),可以查看到js_John的存储格式为str
type(js_John)
Out[22]: str
with open('json_data.json','w') as fp_write:
json.dump(python_John, fp_write)
js_save_John = json.load(open('json_data.json','r'))
查看存储后提取的结果,为字典类型dict
type(js_save_John)
Out[32]: dict
2.2 反序列化load()与loads()
load(obj,fp)
:将json数据解析为python数据,并将数据自动识别为相应的类型存储到python的操作空间中
loads(obj)
:除了没有指定存储路径外,功能及各参数与load()相同。