为什么json.load无法读取?

时间:2019-08-06 13:37:48

标签: python json syntax-error

json不能读超过1本字典。

代码:

with open('jsonfile.json', 'r') as a:
    o = json.load(a)
    print(o)

jsonfile.json:

{
    "1234567899": {
        "username": "1",
        "password": "1",
        "email": "example@example.com"
    }
},
{
    "9987654321": {
        "username": "2",
        "password": "2",
        "email": "example@example.com"
    }
}

错误:

File "unknown", line 8

    {
    ^ SyntaxError: invalid syntax

为什么,不能用于分隔json词典?

2 个答案:

答案 0 :(得分:3)

由于它是无效的JSON,因此会导致错误。一种解决方案是拥有一本整体词典:

{
    "1234567899": {
        "username": "1",
        "password": "1",
        "email": "example@example.com"
    },
    "9987654321": {
        "username": "2",
        "password": "2",
        "email": "example@example.com"
    }
}

另一个是要列出包含您的各种词典的列表:

[{
    "1234567899": {
        "username": "1",
        "password": "1",
        "email": "example@example.com"
    }
},
{
    "9987654321": {
        "username": "2",
        "password": "2",
        "email": "example@example.com"
    }
}]

答案 1 :(得分:0)

用逗号分隔对象,但是json.load期望文件的内容是单个 JSON值,而不是逗号分隔的值。

最简单的解决方法是先将内容包装在方括号中,以产生单个JSON数组。

import json
from itertools import chain


with open('jsonfile.json', 'r') as a:
    contents = chain(['['], a, [']'])
    o = json.loads(''.join(contents))
    print(o)