当前位置 博文首页 > 小龙狗的博客:Python读写Json文件

    小龙狗的博客:Python读写Json文件

    作者:[db:作者] 时间:2021-07-09 18:59

    主要方法

    了解下面这 4 个 Python 的方法,处理 json 基本读写转换就没问题了。

    • dump() 将字典数据写入到 json 文件
    • load() 读取 json 文件,返回字典格式
    • dumps() 将字典格式数据转换成 json 字符串
    • loads() 将 json 字符串转换成字典格式

    代码测试

    test.py如下

    import json 
    def WriteJson():
        # 将字典数据写入到json文件中
        print('写Json:')
        dict1 = {'name': '小明', 'age': 5, 'sex': '男'}
        with open('test.json','w',encoding='utf8')as fp:
            #ensure_ascii=False 就不会用 ASCII 编码,中文就可以正常显示了
            json.dump(dict1,fp,ensure_ascii=False)
    def ReadJson():
        # 读取json文件内容,返回字典格式
        print('读Json:')
        with open('test.json','r',encoding='utf8')as fp:
            json_data = json.load(fp)
        print(json_data)
        print(type(json_data))
    def Dict2Str():
        # 将字典格式数据转换成json格式
        print('dit转str:')
        dict1 = {'name': '小明', 'age': 5, 'sex': '男'}
        print(json.dumps(dict1,ensure_ascii=False))
        print(type(json.dumps(dict1,ensure_ascii=False)))
    def Str2Dict():
        # 将json字符串转换成字典格式
        print('str转dict:')
        str1 = '{"name": "小明", "age": 5, "sex": "男"}'
        print(json.loads(str1))
        print(type(json.loads(str1)))
    
    if __name__ == "__main__":
        WriteJson()
        ReadJson()
        Dict2Str()
        Str2Dict()
    

    运行结果

    D:\> python test.py
    写Json:
    读Json:
    {'name': '小明', 'age': 5, 'sex': '男'}
    <class 'dict'>
    dit转str:
    {"name": "小明", "age": 5, "sex": "男"}
    <class 'str'>
    str转dict:
    {'name': '小明', 'age': 5, 'sex': '男'}
    <class 'dict'>
    
    cs