本质上,我的任务是首先从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])
然后,您需要在收割机中将其弄平。使用展extend
平table_data
。zip()
是组合两个列表的一种更简便的方法,当一个或另一个列表用尽时将停止:
combined = []
for j, t in zip(json_data, table_data):
combined.append(j)
combined.extend(t)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句