本文介绍了python的每个Json文件的连接/合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个Json文件,我想合并/合并并制作一个Json文件.下面的代码使我出错

I have multiple Json files and I want to concat / Merge and make that one Json files.Below code is throwing me an error

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文件的代码

Below is the code for my input json file

if __name__ == '__main__':
        allFiles = []
        while(True):
            inputExtraFiles = input('Enter your other file names. To Ignore    this, Press Enter!: ')
            if inputExtraFiles =='':
                break
            else:
                allFiles.append(inputExtraFiles)
        merge_JsonFiles(allFiles)

但是它给我抛出了一个错误

But it is throwing me an error

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

此外,我想确保如果从控制台仅获取一个输入文件,则json的合并不应引发错误.

Also, I want to make sure that if it gets only one input file from the console, the merging of json should not throw the error.

任何帮助,为什么这会引发错误?

Any help, why is this throwing an error ?

更新

事实证明它返回了一个空的Mergedjson文件.我有有效的json格式

it turns that it returning me an empty Mergedjson files. I have valid json format

推荐答案

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

The error message json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) indicates that your JSON file is malformed or even empty. Please double-check that the files are valid JSON.

此外,没有充分的理由将您的filename参数设置为变长参数列表:

Also, there's no good reason for your filename parameter to be a variable-length argument list:

def merge_JsonFiles(*filename):

删除*运算符,以便实际上可以根据filename列表读取JSON文件.

Remove the * operator so that your JSON files can actually be read according to the filename list.

def merge_JsonFiles(filename):

这篇关于python的每个Json文件的连接/合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:23