在Python中合并多个JSON文件的问题

在Python中合并多个JSON文件的问题,第1张

在Python中合并多个JSON文件的问题

You can’t just concatenate two JSON strings to make valid
JSON
(or combine them by tacking

',n'
to the end of
each). Instead, you could combine the two (as Python objects) into a Python
list, then use
json.dump
to write
it to a file as JSON:

import jsonimport globresult = []for f in glob.glob("*.json"):    with open(f, "rb") as infile:        result.append(json.load(infile))with open("merged_file.json", "wb") as outfile:     json.dump(result, outfile)

If you wanted to do it without the (unnecesssary) intermediate step of parsing
each JSON file, you could merge them into a list like this:

import globread_files = glob.glob("*.json")with open("merged_file.json", "wb") as outfile:    outfile.write('[{}]'.format(        ','.join([open(f, "rb").read() for f in read_files])))


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5031113.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存