第5.1章 json文件操作

json数据示例

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

python与json文件数据类型对比

 
python json
dict {}
list,tuple []
str string
int,float number
True/False true/false
None null

示例

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)

 

posted @ 2018-05-05 15:14  白小白001  阅读(120)  评论(0编辑  收藏  举报