合并/合并每个Json文件,python

2024-10-03 04:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

Json/I要合并多个文件。 下面的代码向我抛出一个错误

def merge_JsonFiles(*filename):
    result = []
    for f1 in filename:
        with open(f1, 'rb') as infile:
            result.append(json.load(infile))

    with open('Mergedjson.json', 'wb') as output_file:
        json.dump(result, output_file)

    # in this next line of code, I want to load that Merged Json files
    #so that I can parse it to proper format
    with open('Mergedjson.json', 'rU') as f:
        d = json.load(f)

下面是我输入json文件的代码

^{pr2}$

但这给了我一个错误

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

另外,我希望确保如果它只从控制台获取一个输入文件,那么json的合并不会抛出错误。在

有什么帮助吗,为什么会抛出错误?在

更新

它返回给我一个空的Mergedjson文件。我有有效的json格式


Tags: 文件代码injsonvalueas错误with
1条回答
网友
1楼 · 发布于 2024-10-03 04:27:28

错误消息json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)表示您的JSON文件格式错误甚至为空。请仔细检查文件是否为有效的JSON。在

另外,您的filename参数不是可变长度的参数列表:

def merge_JsonFiles(*filename):

删除*运算符,这样就可以根据filename列表读取JSON文件。在

^{pr2}$

相关问题 更多 >