我想将多个json文件合并为python中的一个文件。我想做的事情是是否有几个.json文件,例如:
# temp1.json
[{'num':'1', 'item':'smartphone','data':'2019-01-01'},
{'num':'2', 'item':'smartphone','data':'2019-01-02'},
{'num':'3', 'item':'smartphone','data':'2019-01-03'},
{'num':'4', 'item':'smartphone','data':'2019-01-04'}]
# temp2.json
[{'num':'5', 'item':'smartphone','data':'2019-01-05'},
{'num':'6', 'item':'smartphone','data':'2019-01-06'},
{'num':'7', 'item':'smartphone','data':'2019-01-07'}]
# temp3.json
[{'num':'8', 'item':'smartphone','data':'2019-01-08'},
{'num':'9', 'item':'smartphone','data':'2019-01-09'},
{'num':'10', 'item':'smartphone','data':'2019-01-10'},
{'num':'11', 'item':'smartphone','data':'2019-01-11'},
{'num':'12', 'item':'smartphone','data':'2019-01-12'}]
我要获取的result.json文件应如下所示:
# result.json
[{'num':'1', 'item':'smartphone','data':'2019-01-01'},
{'num':'2', 'item':'smartphone','data':'2019-01-02'},
{'num':'3', 'item':'smartphone','data':'2019-01-03'},
{'num':'4', 'item':'smartphone','data':'2019-01-04'},
{'num':'5', 'item':'smartphone','data':'2019-01-05'},
{'num':'6', 'item':'smartphone','data':'2019-01-06'},
{'num':'7', 'item':'smartphone','data':'2019-01-07'},
{'num':'8', 'item':'smartphone','data':'2019-01-08'},
{'num':'9', 'item':'smartphone','data':'2019-01-09'},
{'num':'10', 'item':'smartphone','data':'2019-01-10'},
{'num':'11', 'item':'smartphone','data':'2019-01-11'},
{'num':'12', 'item':'smartphone','data':'2019-01-12'}]
我得到的result.json文件是:
# result.json
[[{'num':'1', 'item':'smartphone','data':'2019-01-01'},
{'num':'2', 'item':'smartphone','data':'2019-01-02'},
{'num':'3', 'item':'smartphone','data':'2019-01-03'},
{'num':'4', 'item':'smartphone','data':'2019-01-04'}],
[{'num':'5', 'item':'smartphone','data':'2019-01-05'},
{'num':'6', 'item':'smartphone','data':'2019-01-06'},
{'num':'7', 'item':'smartphone','data':'2019-01-07'}],
[{'num':'8', 'item':'smartphone','data':'2019-01-08'},
{'num':'9', 'item':'smartphone','data':'2019-01-09'},
{'num':'10', 'item':'smartphone','data':'2019-01-10'},
{'num':'11', 'item':'smartphone','data':'2019-01-11'},
{'num':'12', 'item':'smartphone','data':'2019-01-12'}]]
我使用代码合并了来自这里的.json文件,并将其更改为如下所示:
files=['my.json','files.json',...,'name.json']
def merge_JsonFiles(filename):
result = list()
for f1 in filename:
with open(f1, 'r') as infile:
result.append(json.load(infile))
with open('counseling3.json', 'w') as output_file:
json.dump(result, output_file)
merge_JsonFiles(files)
我已经阅读了几个相关的问题,但是没有答案。谁能帮我?
分析解答
您应该使用extend
而不是append
。它将传递的列表项添加到result
而不是新列表:
files=['my.json','files.json',...,'name.json']
def merge_JsonFiles(filename):
result = list()
for f1 in filename:
with open(f1, 'r') as infile:
result.extend(json.load(infile))
with open('counseling3.json', 'w') as output_file:
json.dump(result, output_file)
merge_JsonFiles(files)