首页 > 解决方案 > 如何使用 python 将列表中的信息填充到多个 JSON 对象中?

问题描述

本质上,有一个 JSON 对象列表,subfolders它需要保存来自 2 个文件的信息——一个来自一个名为的列表json_files,另一个存储在一个名为table_files.

来自json_files并且table_files需要在每个 JSON 对象中按顺序包含一次的信息。

到目前为止,我能够输出我的 JSON 对象列表和要分别保存在这些对象中的信息,但不能以我需要的格式一起输出,这就是问题所在。

我输出subfolders列表的代码:

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))

标签: pythonjsonlistfileobject

解决方案


你可以试试以下方法:

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)

推荐阅读