我有很多类似以下的JSON文件:
例如
1.json
{"name": "one", "description": "testDescription...", "comment": ""}
test.json
{"name": "test", "description": "testDescription...", "comment": ""}
two.json
{"name": "two", "description": "testDescription...", "comment": ""}
...
我想将它们全部合并到一个JSON文件中,例如:
merge_json.json
{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}
我有以下代码:
import json
import glob
result = []
for f in glob.glob("*.json"):
with open(f, "r") as infile:
try:
result.append(json.load(infile))
except ValueError as e:
print(f,e)
result = '\n'.join(result)
with open("merged.json", "w", encoding="utf8") as outfile:
json.dump(result, outfile)
我可以合并所有文件,但是所有内容都在同一行中,在添加每个文件后如何添加换行符:
代替:
{"name": "one", "description": "testDescription...", "comment": ""},{"name": "test", "description": "testDescription...", "comment": ""},{"name": "two", "description": "testDescription...", "comment": ""}
具有以下特征:
merge_json.json
{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}
非常感谢您的帮助。
答案 0 :(得分:1)
result = []
for f in glob.glob("*.json"):
with open(f, "r") as infile:
try:
result.append(json.load(infile))
except ValueError as e:
print(f,e)
with open("merged.json", "a", encoding="utf8") as outfile:
for i in result:
json.dump(i, outfile)
outfile.write('\n')