【问题标题】:Merge multiple json files in one json file将多个json文件合并到一个json文件中
【发布时间】: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'

感谢任何帮助。

【问题讨论】:

标签: python json


【解决方案1】:

模式中的b以二进制模式打开文件。

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

但是json.dump 写入的是字符串,而不是字节。那是因为它可能包含 unicode 字符,并且超出了json 的编码范围(例如utf8)。您可以通过删除b 来简单地以文本形式打开输出文件。

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2019-12-16
    • 2016-12-15
    • 2021-08-13
    • 2016-05-18
    相关资源
    最近更新 更多