【问题标题】:How to populate information from a list into multiple JSON objects using python?如何使用 python 将列表中的信息填充到多个 JSON 对象中?
【发布时间】:2020-02-24 03:02:36
【问题描述】:

基本上有一个名为 subfolders 的 JSON 对象列表,它需要保存来自 2 个文件的信息 - 1 个来自名为 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))

【问题讨论】:

  • 如何获得json_files 和table_files
  • 编辑了我原来的帖子。基本上通过子目录并将它们附加到基于后缀的列表中

标签: python json list file object


【解决方案1】:

您可以尝试以下方法吗:

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)

【讨论】:

  • 这实际上是一个小错误——不是一次只填充 1 个json_data 和 1 个table_data 文件的信息,而是一次为每个 JSON 对象填充整个列表。如果您可以编辑答案以反映这一点并一次将其作为 1 个文件,那就太好了,谢谢
  • 子目录里面会有多个 json 文件,如果是的话你想要怎样的输出
  • 在每个子目录中,应该有 1 个 JSON 文件和 1 个 .list 文件。输出应与每个对象内的 1 个 JSON 文件和 1 个 .list 文件中的信息相同
  • 请解释你的答案。
猜你喜欢
  • 2020-08-03
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多