首页 > 解决方案 > 在字典中创建字典以将其转换为 Json 数据

问题描述

我的工作流程是,我将在不同的文件中有一些字典,我会将它们调用到一个文件中,比如说 demo.py。我在 demo.py 中有一个变量 temp_dict,其中来自不同文件的字典将被一一附加。例子 ::::

    {
        "Action": None,
        "Parameter": "abc",
        "ParameterDescription": "def",
        "ExpectedValue": "ghi",
         {
            "Extensions":"jkl",
            "MappedData": "no",
            "Parameters": "pqr",
            "Labels": "Stu",
         }    
         {  
            "Recorder": "abc",
            "Diagnostics": "efg",
            "AdditionalRemarks": ""
         }

    } 
     

我想要这种类型的结构,我需要在字典中附加字典,我该怎么做。

我还将提供python代码

    # function to add data to JSON
    def write_json(new_data, filename='report.JSON'):
        # new_data is the dictioanries coming from other files, it will be converted into json and dump it into a file.
        
       with open(filename, 'w') as f:
           json_string=json.dumps(new_data)
           f.write(json_string)
    

提前致谢

标签: pythonjson

解决方案


您提供的数据不是有效的 python 字典,也不是有效的 JSON。

字典和 JSON 是key: value对的。该值可能是嵌套字典/JSON,但是在您的示例中,嵌套字典没有键。

但是,这样的事情会起作用:

{
  "Action": None,
  "Parameter": "abc",
  "ParameterDescription": "def",
  "ExpectedValue": "ghi",
  "YOU NEED SOME NAME HERE": {
    "Extensions":"jkl",
    "MappedData": "no",
    "Parameters": "pqr",
    "Labels": "Stu",
  },
  …
}

您可能一直在考虑数组中的 json 对象/字典。那里的字典不必命名,但那是因为它们隐含了一个名称——它们在有序数组中的索引(位置)

[
  {
    "name": "Faboor",
    "type": "user"
  },
  {
    "name": "prithvi"
    "reputation": 19
  }
]

推荐阅读