【问题标题】:Merge multiple JSON files (more than two)合并多个 JSON 文件(两个以上)
【发布时间】:2019-03-23 13:38:07
【问题描述】:

我想将多个 JSON 文件合并到一个文件中。所有这些文件都具有相同的结构。例如,我创建了三个如下所示的文件:

ExampleFile_1

    {
      "items": [
        {
          "answers": [
            {
              "creation_date": 1538172165
            },
            {
              "creation_date": 1538172205
            },
            {
              "creation_date": 1538172245
            }
         ],
       "creation_date": 1538172012,
       "question_id": 52563137
       }
      ]
    }

ExampleFile_2

    {
      "items": [
        {
          "answers": [
            {
              "creation_date": 1538326991
            }
          ],
        "creation_date": 1538172095,
        "question_id": 52563147
        },
        {
          "answers": [
            {
              "creation_date": 1538180453
            }
          ],
        "creation_date": 1538172112,
        "question_id": 52563150
        }
      ]
    }

ExampleFile_3

   {
       "items": [
          {
            "answers": [
              {
                 "creation_date": 1538326991
              }
            ],
              "creation_date": 1538172095,
              "question_id": 52563147
           }
        ]
     }

现在我想将"items" 列表中的所有三个文件合并到一个文件中,然后如下所示:

merged_json.json

   {
       "items": [
        {
         "answers": [
            {
              "creation_date": 1538172165
            },
            {
              "creation_date": 1538172205
            },
            {
              "creation_date": 1538172245
            }
          ],
            "creation_date": 1538172012,
            "question_id": 52563137
          },
          {
            "answers": [
             {
               "creation_date": 1538326991
             }
            ],
           "creation_date": 1538172095,
           "question_id": 52563147
          },
          {
           "answers": [
             {
               "creation_date": 1538180453
             }
            ],
            "creation_date": 1538172112,
            "question_id": 52563150
          },
          {
            "answers": [
              {
                 "creation_date": 1538326991
              }
            ],
            "creation_date": 1538172095,
            "question_id": 52563147
           }
        ]
     }

所以像上面一样,"items" 应该被连接起来。

我已经尝试想出一个解决方案,但无法弄清楚。 这是我到目前为止得到的:

read_files = glob.glob("ExampleFile*.json")
output_list = []

for f in read_files:
    with open(f, "rb") as infile:
        output_list.append(json.load(infile))

all_items = []
for json_file in output_list:
    all_items += json_file['items']

textfile_merged = open('merged_json.json', 'w')
textfile_merged.write(str(all_items))
textfile_merged.close()

不幸的是,这给我留下了一个混乱的 json 文件,它只包含 "items" 中的字典。

如何创建像merged_json.json 这样的文件?

提前致谢。

【问题讨论】:

    标签: json python-3.x list dictionary merge


    【解决方案1】:

    您正在使用 json 模块将 JSON 文件转换为 Python 对象,但您没有使用该模块将这些 Python 对象back 转换为 JSON。最后不是这个

    textfile_merged.write(str(all_items))
    

    试试这个:

    json.dump({ "items": all_items }, textfile_merged)
    

    (请注意,这也是将 all_items 数组包装在字典中,以便您获得预期的输出,否则输出将是 JSON 数组,而不是带有 "items" 键的对象)。

    【讨论】:

      【解决方案2】:

      一种你可以做到的方式,这将导致更简洁的代码来定义一个函数,该函数接受两个 JSON 对象并返回这两个对象的组合。

      def merge (json_obj_1, json_obj_2):
          items = json_obj_1['items'] + json_obj_2['items']
          return { 'items': items }
      

      然后,在你有 output_list 之后:

      result = reduce(merge, output_list)
      

      结果将是您要查找的对象。

      如果您不熟悉 reduce 功能,请查看此网页:

      http://book.pythontips.com/en/latest/map_filter.html

      简要说明reduce的用法,以及map和filter的用法。它们非常有用。

      【讨论】:

        【解决方案3】:
        read_files = glob.glob("ExampleFile*.json")                                                                                                                                                                         
        output_list = []                                                                                                                                                                                                    
        
        for f in read_files:                                                                                                                                                                                                
        with open(f, "rb") as infile:                                                                                                                                                                                     
           output_list.append(json.load(infile))                                                                                                                                                                           
        
        final_json = {}                                                                                                                                                                                                                                                                                                                                                                                             
        all_items = []                                                                                                                                                                                                      
        for json_file in output_list:                                                                                                                                                                                       
           all_items.extend(json_file['items'])                                                                                                                                                                              
        
        final_json['items'] = all_items                                                                                                                                                                                     
        
        textfile_merged = open('merged_json.json', 'w')                                                                                                                                                                     
        textfile_merged.write(str(final_json)) 
        

        【讨论】:

          【解决方案4】:

          我建议您使用json,它专门用于 JSON 对象操作。你可以这样做:

              import json
          
          with open('example1.json') as f:
              data1 = json.load(f)
          
          with open('example2.json') as f:
              data2 = json.load(f)
          
          with open('example3.json') as f:
              data3 = json.load(f)
          
          items1 = data1["items"]
          #print(json.dumps(items1, indent=2))
          items2 = data2["items"]
          items3 = data3["items"]
          
          listitem = [items1, items2, items3]
          finaljson = {"items" : []}
          
          finaljson["items"].append(items1)
          finaljson["items"].append(items2)
          finaljson["items"].append(items3)
          print(json.dumps(finaljson, indent=2))
          
          with open('merged_json.json', "w") as f:
              f.write(json.dumps(finaljson, indent=2))
          

          其中json.load() 将字符串转换为json 对象,而json.dumps() 将json 转换为字符串。参数indent让你以扩展的方式打印对象。

          【讨论】:

            【解决方案5】:

            如果只想顺序合并所有json文件,

            1. 转到所有 json 文件所在的文件夹,全选并将第一个重命名为“yourchoice”,这样做所有将按顺序排列,即 yourchoice1,yourchoice2 ...

            2. 接下来进入 cmd 并输入:复制 *.json "outputfilename".json

            3. 您所有的 json 文件都按顺序合并到 "outputfilename".json 文件中

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-09-19
              • 2016-05-18
              • 1970-01-01
              • 2021-08-13
              • 2015-09-01
              • 1970-01-01
              • 2019-11-13
              • 1970-01-01
              相关资源
              最近更新 更多