解析多个 json 文件,展平数据并另存为 json
Parse multiple json files, flatten data and save as json
我在一个文件夹中保存了多个 json 个文件。我想解析每个 json 文件,使用库展平并另存为单独的 json 文件。
我已经设法用一个 json 做到了这一点,但在不合并数据然后保存的情况下,很难同时解析多个 json 文件。
我想我需要创建一个循环来加载 json 文件,展平并保存直到文件夹中不再有 json 文件,这可能吗?
这似乎仍然只能解析一个 json 文件。
path_to_json='json_test/'
for file in [file for file in os.listdir(path_to_json)if file.endswith('.json')]:
with open(path_to_json + file) as json_file:
data1=json.load(json_file)
任何帮助将不胜感激谢谢!
# Can yo try this out
#
import glob
read_files = glob.glob("*.json")
with open("merged_file.json", "wb") as outfile:
outfile.write('[{}]'.format(
','.join([open(f, "rb").read() for f in read_files])))
每个循环 'data1' 都分配给新的 json 文件。因此只有 returns 个结果。
相反,附加到新列表。
import os
import json
# Flatten not supported on 3.8.3
path = 'X:test folder/'
file_list = [p for p in os.listdir(path) if p.endswith('.json')]
flattened = []
for file in file_list:
with open(path + file) as json_file:
# flatten json here, can't install from pip.
flattened.append(json.load(json_file))
for file, flat_json in zip(file_list, flattened):
json.dump(flat_json, open(path + file + '_flattened.json', "w"), indent=2)
我在一个文件夹中保存了多个 json 个文件。我想解析每个 json 文件,使用库展平并另存为单独的 json 文件。
我已经设法用一个 json 做到了这一点,但在不合并数据然后保存的情况下,很难同时解析多个 json 文件。
我想我需要创建一个循环来加载 json 文件,展平并保存直到文件夹中不再有 json 文件,这可能吗?
这似乎仍然只能解析一个 json 文件。
path_to_json='json_test/'
for file in [file for file in os.listdir(path_to_json)if file.endswith('.json')]:
with open(path_to_json + file) as json_file:
data1=json.load(json_file)
任何帮助将不胜感激谢谢!
# Can yo try this out
#
import glob
read_files = glob.glob("*.json")
with open("merged_file.json", "wb") as outfile:
outfile.write('[{}]'.format(
','.join([open(f, "rb").read() for f in read_files])))
每个循环 'data1' 都分配给新的 json 文件。因此只有 returns 个结果。 相反,附加到新列表。
import os
import json
# Flatten not supported on 3.8.3
path = 'X:test folder/'
file_list = [p for p in os.listdir(path) if p.endswith('.json')]
flattened = []
for file in file_list:
with open(path + file) as json_file:
# flatten json here, can't install from pip.
flattened.append(json.load(json_file))
for file, flat_json in zip(file_list, flattened):
json.dump(flat_json, open(path + file + '_flattened.json', "w"), indent=2)