【python】json的日常操作

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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值