Python中的JSON数据处理

1.JSON

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,表示实体的属性关系。

  • 以“名称 : 值”的格式存储;
  • 写入和读取都按照dict的类型,区别于csv文件的字符串类型;
  • json本质上使用字符串类型进行存储,但是load方法可以在读取时自动解析出数据类型;
  • jsondict本质上时不同的,json是一种文件的组织方式,而dict是程序语言中定义的一种数据结构
  • python中的TrueNone分别对应json中的truenull
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()相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值