在一个json文件中合并多个json文件

时间:2018-10-04 19:58:59

标签: python json

我有很多类似以下内容的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, "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'

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

该模式下的|S10以二进制模式打开文件。

b

但是with open("merged_file.json", "wb") as outfile: 写入一个字符串,而不是字节。这是因为它可能包含unicode字符,并且超出了json.dump的编码范围(例如,到json的编码范围)。您只需删除utf8,即可将输出文件作为文本打开。

b

它将使用默认文件编码。您也可以使用open命令指定编码。例如:

with open("merged_file.json", "w") as outfile:

出于相同的原因,您还应该以文本模式打开文件:

with open("merged_file.json", "w", encoding="utf8") as outfile: