首页 > 解决方案 > Why does json.load not read this?

问题描述

json can't read more than 1 dictionary.

Code:

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"
    }
}

Error:

File "unknown", line 8

    {
    ^ SyntaxError: invalid syntax

Why does the , not work to separate the json dictionaries?

标签: pythonjsonsyntax-error

解决方案


It is causing an error because it is an invalid JSON. One solution is to have one overall dictionary:

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

Another is to have a list containing your various dictionaries:

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

推荐阅读