首页 > 解决方案 > 如何使用 python 以交替方式组合来自 .json 和 .list 文件的数据以转储到新的 JSON 文件中?

问题描述

本质上,我的任务是先从 JSON 文件中提取信息,然后再从 .list 文件中提取信息。然后,此信息以交替顺序转储到名为summary.json.

到目前为止,我的方法是将所有 json 数据提取到一个列表中,然后将列表数据提取到另一个列表中。从那里,我一次将所有 1 个索引的信息添加到要转储的新组合列表中。

# append json_data to list1
json_data = []
for i in json_files:
    with open(i) as f:
        json_data.append(json.load(f))

# append table_data to list2
table_data = []
for i in table_files:
    with open(i) as f:
        for line in f:
            table_data.append(line)

#format data to remove \n characters
table_data = [sub.replace('\n', '') for sub in table_data]

#combine list info
combined = []
while True:
    try:
        combined.append(json_data.pop(0))
        combined.append(table_data.pop(0))
    except IndexError:
        break

# dump list info to new json file
with open('summary.json', 'w') as f:
    json.dump(combined, f, indent=2)

这是我当前代码的输出:

[
  {
    "json_object1_item1": "value1",
    "json_object1_item2": "value2",
    "json_object1_item3": "value3"
  },
  tablelist1_item1,
  {
    "json_object2_item1": "value1",
    "json_object2_item2": "value2",
    "json_object2_item3": "value3"
  }
 tablelist1_item2
]

所需的输出类似于:

[
  {
    "json_object1_item1": "value1",
    "json_object1_item2": "value2",
    "json_object1_item3": "value3"
  },
  tablelist1_item1,
  tablelist1_item2,
  tablelist1_item3,
  {
    "json_object2_item1": "value1",
    "json_object2_item2": "value2",
    "json_object2_item3": "value3"
  }
 tablelist2_item1,
 tablelist2_item2,
 tablelist2_item3
]

如何修复我的代码以获得我需要的东西?有没有更好的方法来实现我的输出?谢谢

标签: pythonjsonlistfile

解决方案


您仅从 中获得一个值的原因table_data是因为您已将其展平,例如,[1,2,3,4,5,6]而不是[[1,2],[3,4],[5,6]],例如:

table_data = []
for i in table_files:
    with open(i) as f:
        table_data.append([line.rstrip('\n') for line in f])

然后你需要在你的联合收割机中把它弄平。的使用extend使table_data. zip()是组合两个列表的一种更简单的方法,并且会在一个或另一个列表用完时停止:

combined = []
for j, t in zip(json_data, table_data):
    combined.append(j)
    combined.extend(t)

推荐阅读