本质上有一个名为 subfolders
的 JSON 对象列表,它需要保存来自 2 个文件的信息 - 一个来自名为 json_files
的列表,另一个存储在名为 json_files
的列表中table_files
。
来自 json_files
和 table_files
的信息需要在每个 JSON 对象中按顺序各包含一次。
到目前为止,我能够分别输出 JSON 对象列表和这些对象中要保存的信息,但无法以我需要的格式一起输出,这就是问题所在。
我用于输出子文件夹
列表的代码:
subfolders = [ f.path for f in os.scandir(rootdir) if f.is_dir() ]
subfolders = [sub.replace(rootdir + '\\', '') for sub in subfolders]
obj = { conf_name:{} for conf_name in subfolders }
with open('summary.json', 'w') as f:
json.dump(obj, f, indent=2)
用于输出要存储在子文件夹中的 json_data
和 table_data
信息的代码:
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
combined = []
for j, t in zip(json_data, table_data):
combined.append(j)
combined.extend(t)
with open('summary.json', 'w') as f:
json.dump(combined, f, indent=2)
期望的输出:
{
"subfolder1": {
"json_data": "{content from first json_data file in list}"
"table_data": "content from first table_data file in list"
},
"subfolder2": {
"json_data": "{content from second json_data file in list}"
"table_data": "content from second json_data file in list"
}
}
因此,我想知道如何将所有内容组合在一起以生成我需要的格式。非常感谢任何帮助,谢谢。
编辑:用于获取json_files
和table_files
列表:
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
最佳答案
您可以尝试以下操作吗:
summary = {}
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
summary[subdir] = {
'json_data': json_data,
'table_data': table_data
}
with open('summary.json', 'w') as f:
json.dump(summary, f, indent=2)
关于python - 如何使用 python 将列表中的信息填充到多个 JSON 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60369028/