第5.1章 json文件操作

本文介绍了Python中如何处理JSON数据,包括将Python数据结构转换为JSON字符串,从JSON字符串加载到Python数据结构的方法,以及如何读写JSON文件。

json数据示例

{
    "single": {
        "is_guest_record": 0,
        "kms": [],
        "path": [{
            "time": 1509708120,
        }],
        "pc_type": "OPPO R9s"
    }
}

python与json文件数据类型对比

 
pythonjson
dict{}
list,tuple[]
strstring
int,floatnumber
True/Falsetrue/false
Nonenull

示例

import json

python_dict = {'id':10,'name':'li4','likes':['看书','游戏'],'study':{'AI':('python','Ruby'),'大数据':('kafka',)},'if_vip':True}

# python数据转换为json类型字符串
json_str = json.dumps(python_dict,ensure_ascii=False)
print(json_str)
print(type(json_str))

# json字符串转换为python数据
python_data = json.loads(json_str)
print(python_data)
print(type(python_data))

# python数据转换为json类型字符串,并写入json文件
with open('file/jsonfile.json','w',encoding='utf-8') as f:
    json.dump(python_dict,f,ensure_ascii=False)

# 读取json文件,并将json字符串转换为python数据
with open('file/jsonfile.json','r',encoding='utf-8') as f:
    python_data1 = json.load(f)
    print(python_data1)

 

转载于:https://www.cnblogs.com/bxbyy/p/8994804.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值