python - 如何使用 python 将列表中的信息填充到多个 JSON 对象中?

标签 python json list file object

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

来自 json_filestable_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_datatable_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_filestable_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/

相关文章:

Python:如何访问调用模块中的变量?

php - 使用 PHP GET 服务器

json - Elasticsearch 术语过滤器引发 "filter does not support [mediatest]"

arrays - Perl 列表中的多散列

c# - 如何继续将整数添加到列表中,同时查看这些整数是否已经在列表中?

python - 在单独的标签文本中使用时,变量具有不同的值

python - PyGame,如何创建带有文本的按钮?

python - 如何从字典的值中删除 '\n'

json - 使用 jq 从 bash 中管道分隔的键和值创建 JSON

java - 为 customClass 列表定义方法