Python JSON操作

Json 模块的四个方法

dumps():将dict数据转化成json数据(Python里是str类型)

loads():将json数据转化成dict数据(Python里是dict类型)

load():读取json文件数据,转成dict数据

dump():将dict数据转化成json数据后写入json文件

示例代码

点击查看代码
import json
def dict_to_json():
    dict1={}
    dict1['name']='tom'
    dict1['age']=20
    dict1['sex']='male'
    print(dict1)
    jsons=json.dumps(dict1)
    print(jsons)
    print(type(jsons))

def json_to_dict():
    jsons = '{"name": "Tom", "age": 28, "sex": "male", "phone": "123456", "email": "Tom@126.com"}'
    dict1= json.loads(jsons)
    print(dict1)
    print(type(dict1))

def dict_to_json_write_file():
    dict = {}
    dict['name'] = 'tom'
    dict['age'] = 10
    dict['sex'] = 'male'
    print(dict)
    with open('test.json', 'w', encoding="utf-8") as f:
        json.dump(dict, f,indent=2)

def json_file_to_dict():
    with open('test.json', 'r') as f:
        dict1 = json.load(f)
        print(dict1)
        print(type(dict1))

if __name__ == '__main__':
    dict_to_json()
    json_to_dict()
    dict_to_json_write_file()
    json_file_to_dict()

参考链接

如何在Python中使用JSON数据 (qq.com)

Python处理JSON数据 (qq.com)

posted @ 2021-12-04 16:08  Dapenson  阅读(146)  评论(0编辑  收藏  举报