美文网首页大数据 爬虫Python AI SqlPythonPython编程
Python实现字典 dict 和 json 相互转化

Python实现字典 dict 和 json 相互转化

作者: 傻逼平台瞎几把封号 | 来源:发表于2022-07-22 15:16 被阅读0次

    字典 dict 和 json 如何相互转化, 将字典数据转 json 格式写入文件,然后从文件中读取出来还原为字典。

    知识点

    • 文件读写
    • 基础语法
    • 多级字典
    • json

    代码展示

    使用的模块

    import platform
    import json
    

    输入多级字典数据

    input_dict = {
        "students": [
            {"name": "John", "age": "15"},
            {"name": "Anna", "age": "16"},
            {"name": "Peter", "age": "16"}
        ],
        "teachers": [
            {"name": "Jack", "age": "30"},
            {"name": "Jessy", "age": "33"}
        ]}
    
    print("输入数据: ", input_dict)
    
    

    字典 dict 转 json, 写入文件

    def dict_to_json():
    
        with open("py013.json", "w") as f:
            f.write(json.dumps(input_dict, indent=4))
    
    

    json 转 字典 dict , 从文件读取

    def json_to_dict():
    
        with open("py013.json") as f:
            output_dict = json.loads(f.read())
    
    

    全部代码

    import platform
    import json
    
    print("孟曰:如欲平治天下,当今之世,舍我其谁也?")
    print("字典 dict 和 json 如何相互转化 ")
    
    input_dict = {
        "students": [
            {"name": "John", "age": "15"},
            {"name": "Anna", "age": "16"},
            {"name": "Peter", "age": "16"}
        ],
        "teachers": [
            {"name": "Jack", "age": "30"},
            {"name": "Jessy", "age": "33"}
        ]}
    
    print("输入数据: ", input_dict)
    
    def dict_to_json():
    
        with open("py013.json", "w") as f:
            f.write(json.dumps(input_dict, indent=4))
    
    def json_to_dict():
    
        with open("py013.json") as f:
            output_dict = json.loads(f.read())
    
        print("json 转字典的结果: ", output_dict)
    
    dict_to_json()
    
    json_to_dict()
    
    print("Python 版本", platform.python_version())
    
    

    效果展示

    Json 格式数据

    {
        "students": [
            {
                "name": "John",
                "age": "15"
            },
            {
                "name": "Anna",
                "age": "16"
            },
            {
                "name": "Peter",
                "age": "16"
            }
        ],
        "teachers": [
            {
                "name": "Jack",
                "age": "30"
            },
            {
                "name": "Jessy",
                "age": "33"
            }
        ]
    }
    
    

    兄弟们,今天的分享就到这,再见!

    来都来了,点个关注再走呗!

    相关文章

      网友评论

        本文标题:Python实现字典 dict 和 json 相互转化

        本文链接:https://www.haomeiwen.com/subject/srmuirtx.html