简体   繁体   中英

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?

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

The comma does separate the objects, but json.load expects the contents of the file to be a single JSON value, not a comma-separate series of values.

The simplest fix is to wrap the contents in brackets first to produce a single JSON array.

import json
from itertools import chain


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM