【发布时间】:2018-10-05 04:23:17
【问题描述】:
我有很多 json 文件,如下所示:
例如
1.json
{"name": "one", "description": "testDescription...", "comment": ""}
test.json
{"name": "test", "description": "testDescription...", "comment": ""}
两个.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, "rb") as infile:
try:
result.append(json.load(infile))
except ValueError:
print(f)
with open("merged_file.json", "wb") as outfile:
json.dump(result, outfile)
但它不起作用,我有以下错误:
merged_file.json
Traceback (most recent call last):
File "Data.py", line 13, in <module>
json.dump(result, outfile)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\json\__init__.py", line 180, in dump
fp.write(chunk)
TypeError: a bytes-like object is required, not 'str'
感谢任何帮助。
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/a/33054552
-
cat 1.json test.json two.json > merge_json.json