代码之家  ›  专栏  ›  技术社区  ›  user96564

具体化/合并每个JSON文件,python

  •  1
  • user96564  · 技术社区  · 8 年前

    我有多个JSON文件,我想要concat/merge并将其作为一个JSON文件。 下面的代码给了我一个错误

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

    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)
    

    但它给了我一个错误

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

    另外,我想确保如果它只从控制台获取一个输入文件,那么合并JSON不应该抛出错误。

    有什么帮助吗,为什么这会引发错误?

    更新

    它会返回一个空的mergedjson文件。我有有效的JSON格式

    1 回复  |  直到 8 年前
        1
  •  1
  •   blhsing    8 年前

    错误信息 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 指示JSON文件格式不正确,甚至为空。请仔细检查这些文件是否是有效的JSON。

    而且,没有充分的理由 filename 参数为可变长度参数列表:

    def merge_JsonFiles(*filename):
    

    删除 * 运算符,以便可以根据 文件名 列表。

    def merge_JsonFiles(filename):