【问题标题】:Concating / Merging of each Json Files, python连接/合并每个 Json 文件,python
【发布时间】:2018-06-27 06:59:48
【问题描述】:

我有多个 Json 文件,我想连接/合并并制作一个 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 格式

【问题讨论】:

标签: python json python-3.x


【解决方案1】:

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

此外,您的 filename 参数没有充分的理由成为可变长度参数列表:

def merge_JsonFiles(*filename):

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

def merge_JsonFiles(filename):

【讨论】:

  • 我刚查了一下,原来合并的json文件是空的。我正在加载的文件具有正确的 json 格式。
  • @fireandwind 我刚刚用我认为真正的问题编辑了我的答案。
  • 它再次返回相同的空文件,但现在错误不同了,fp.write(chunk) TypeError: a bytes-like object is required, not 'str'
  • @fireandwind 不要以二进制模式打开文件。 JSON 是文本。使用'r''w' 模式以文本模式打开文件。
  • 谢谢你,成功了。对于stackoverflow,这可能是不同的问题。我所有的 json 文件都从 [{"type": "FeatureCollection" 连接开始,但是在每个 json 文件的末尾,我将有 [{"type": "FeatureCollection" 有什么方法可以保留这个吗?一次?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2019-11-13
  • 2021-08-13
  • 1970-01-01
  • 2018-05-23
  • 2023-03-10
相关资源
最近更新 更多