简体   繁体   English

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

[英]Merge multiple json files in one json file

I have alot of json files like the following: 我有很多类似以下内容的json文件:

eg 例如

1.json 1.json

{"name": "one", "description": "testDescription...", "comment": ""}

test.json test.json

{"name": "test", "description": "testDescription...", "comment": ""}

two.json two.json

{"name": "two", "description": "testDescription...", "comment": ""}

...

I want to merge them all in one json file like: 我想将它们全部合并到一个json文件中,例如:

merge_json.json merge_json.json

{"name": "one", "description": "testDescription...", "comment": ""}
{"name": "test", "description": "testDescription...", "comment": ""}
{"name": "two", "description": "testDescription...", "comment": ""}

I have the following code: 我有以下代码:

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)

But it is not working, I have the following error: 但是它不起作用,我有以下错误:

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'

Appreciated for any help. 感谢任何帮助。

The b in the mode opens the file in binary mode. 模式下的b以二进制模式打开文件。

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

But json.dump writes a string, not bytes. 但是json.dump写一个字符串,而不是字节。 That is because it may contain unicode characters and it's outside the scope of json to encode it (eg to utf8 ). 那是因为它可能包含unicode字符,并且不在json的范围内进行编码(例如utf8 )。 You can simply open the output file as text by removing the b . 您只需删除b即可简单地以文本形式打开输出文件。

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

It will use he default file encoding. 它将使用默认文件编码。 You can also specify the encoding with the open command. 您也可以使用open命令指定编码。 eg: 例如:

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

You should also open your file in text mode for the same reasons: 出于相同的原因,您还应该以文本模式打开文件:

with open(f, "r") as infile:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM