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

awdoibbbbbbb2

本质上,我的任务是首先从JSON文件中提取信息,然后再从.list文件中提取信息。然后,此信息将按照交替的顺序转储到名为的新JSON文件中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
]

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

冠军

您仅从中获得一个值的原因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])

然后,您需要在收割机中将其弄平。使用展extendtable_datazip()是组合两个列表的一种更简便的方法,当一个或另一个列表用尽时将停止:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何上传邮差文件和JSON数据?

如何将HashSet转储到Java文件中

Python编码和JSON转储

如何使用pymongo将集合转储到json文件

json如何将tweepy流转储到文本文件中?

在多线程环境中将JSON转储到文件

将json转储到文件中时,键(0,0)不是字符串-Python

如何将泡菜文件转储到新行中?

如何从json文件读取和写入数据

我如何删除转储在我的Yaml文件中的数据中的字符串和int周围的引号

使用python将xml数据转储到csv文件中的单元格中

使用datetime键将字典转储到生成TypeError的json文件

结合使用Ordereddict和默认dict并将其转储到json文件中

如何获取输入到输入框中的信息并将其保存(转储)到文本文件(json)中

如何将多个python对象转储和加载到json文件中或从json文件中加载?

如何使用Javascript将JSON数据转储到JSON文件中?

使用JSON文件中的JS读取和计算数据

如何在将数据转储到其中之前清空json文件

如何将Nutch 2.3数据转储到WARC文件中?

如何将对象列表转储到python django中的json中

密钥的 Json 转储,在 Python 中配对

在python中转储json文件

使用 json 模板文件和 json 数据文件构建新的 json 字符串

Python 将 JSON 对象转储到另一个 JSON 对象中

将中文数据转储到json文件中

如何将用户定义的python对象转储到json文件?我所说的对象是指实际的对象而不是它们的属性

使用 pymongo 读取/解析带有字典列表的 JSON 文件并转储到数据库中

CSV文件转储到python中的yaml文件

缩短此代码...附加来自多个 GET 请求的 JSON 数据,然后转储到带有标题的单个 Excel 文件中