繁体   English   中英

如何从文件夹中打开多个 JSON 文件并将它们合并到 python 中的单个 JSON 文件中?

[英]How to open multiple JSON file from folder and merge them in single JSON file in python?

假设有 3 个文件——data1.json、data2.json、data3.json。

假设 data1.json 包含 -

{ 
   "Players":[ 
      { 
         "name":"Alexis Sanchez",
         "club":"Manchester United"
      },
      { 
         "name":"Robin van Persie",
         "club":"Feyenoord"
      }
   ]
}

data2.json 包含 -

{ 
   "Players":[ 
      { 
         "name":"Nicolas Pepe",
         "club":"Arsenal"
      }
   ]
}

data3.json 包含 -

{ 
   "players":[ 
      { 
         "name":"Gonzalo Higuain",
         "club":"Napoli"
      },
      { 
         "name":"Sunil Chettri",
         "club":"Bengaluru FC"
      }
   ]
}

这 3 个文件的合并将生成一个包含以下数据的文件。 结果.json -

{ 
   "players":[ 
      { 
         "name":"Alexis Sanchez",
         "club":"Manchester United"
      },
      { 
         "name":"Robin van Persie",
         "club":"Feyenoord"
      },
      { 
         "name":"Nicolas Pepe",
         "club":"Arsenal"
      },
      { 
         "name":"Gonzalo Higuain",
         "club":"Napoli"
      },
      { 
         "name":"Sunil Chettri",
         "club":"Bengaluru FC"
      }
   ]
}

如何从文件夹中打开多个 JSON 文件并将它们合并到 python 中的单个 JSON 文件中?

我的方法:

import os, json
import pandas as pd
path_to_json =  #path for all the files.
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

jsons_data = pd.DataFrame(columns=['name', 'club'])

for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)

        name = json_text['strikers'][0]['name']
        club = json_text['strikers'][0]['club']

        jsons_data.loc[index] = [name, club]

print(jsons_data)

这可以为你工作:

import json
import glob
import pprint as pp #Pretty printer

combined = []
for json_file in glob.glob("*.json"): #Assuming that your json files and .py file in the same directory
    with open(json_file, "rb") as infile:
        combined.append(json.load(infile))



pp.pprint(combined)

这正是你想要的,

import json, glob

merged_json = []
for json_file in glob.glob("*json"):
    with open(json_file, "rb") as file:
      json_data = json.load(file)
      if "Players" in json_data:
        merged_json += json_data["Players"]
      else:
        merged_json += json_data["players"]

to_json = json.dumps(merged_json)
print (to_json)

Output

[{"name": "Alexis Sanchez", "club": "Manchester United"}, {"name": "Robin van Persie", "club": "Feyenoord"}, {"name": "Nicolas Pepe", "club": "Arsenal"}, {"name": "Gonzalo Higuain", "club": "Napoli"}, {"name": "Sunil Chettri", "club": "Bengaluru FC"}]

上面的两个答案似乎都有效。 有人可以解释为什么使用“二进制”模式来读取文件而不是只读取文件吗?

以 open(json_file, "rb") 作为输入文件:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM