创建嵌套的 json 文件

我想创建一个可以用作配置文件的json文件。我有来自多个公司的不同文件,这些文件报告具有不同列名称的相同信息。


我想使用json文件中提供的信息来运行python脚本,以将所有文件和公司的所有信息合并到一个主文件中。


结构如下所示:


{"companies":

    {"company1": [

        {"path": "C:/USER/Path/Company1/",

         "files": [

            {

                {"_CO": {"ID": "ID", "Report Number": "Report_Number"}},

                {"_TR": {"ID": "Trade_Ident", "Report Number": "Number of Report"}},    

            },

         ],

        },

    ],

    },


    {"company2": [

        {"path": "C:/USER/Path/Company2/",

         "files": [

            {

                {"_CO": {"ID": "Identification", "Report Number": "Report-Number"}},

                {"_TR": {"ID": "Ident", "Report Number": "NumberReport"}},  

            },

         ],

        },

    ],

    },

},

但是,当我尝试在python中读取.json时,我收到以下错误。


json.decoder.JSONDecodeError:期望属性名称括在双引号中:第 6 行第 5 列(字符 90)


要读取我使用的文件:


import json


path = "/user_folder/USER/Desktop/Data/"


file = "ConfigFile.json"


with open(path+file) as f:

    my_test = json.load(f)

任何帮助都值得赞赏,因为我无法找出我在文件结构中的错误。


Smart猫小萌
浏览 152回答 2
2回答

拉风的咖菲猫

您收到错误,因为您的文件格式不正确,因此调用将引发.jsonjson.load()JSONDecodeError您的结构应如下所示:json{    "companies": {        "company1": [            {                "path": "C:/USER/Path/Company1/",                "files": [                    {                        "_CO": {                            "ID": "ID",                            "Report Number": "Report_Number"                        }                    },                    {                        "_TR": {                            "ID": "Trade_Ident",                            "Report Number": "Number of Report"                        }                    }                ]            }        ],        "company2": [            {                "path": "C:/USER/Path/Company2/",                "files": [                    {                        "_CO": {                            "ID": "Identification",                            "Report Number": "Report-Number"                        }                    },                    {                        "_TR": {                            "ID": "Ident",                            "Report Number": "NumberReport"                        }                    }                ]            }        ]    }}希望它能帮助你!

小怪兽爱吃肉

您有一些对象(带有大括号的对象)没有键,例如在{    {"_CO": {"ID": "ID", "Report Number": "Report_Number"}}, ...JSON 中的对象是键值对。只需取下外部一组大括号,它应该没问题。您可以使用一些在线JSON格式化程序/验证程序,就像这样,它很容易指出问题。否则,您可以为编辑器使用一些 JSON linter。它只是为您完成工作,并改善缩进:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python