-2

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?

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Mike
  • 3
  • 1
  • 8
    I think this is not valid JSON... It should be enclosed in `[ ]`. – Paulo Scardine Aug 06 '19 at 13:40
  • 2
    Possible duplicate of [multiple Json objects in one file extract by python](https://stackoverflow.com/questions/27907633/multiple-json-objects-in-one-file-extract-by-python) – turbulencetoo Aug 06 '19 at 13:40
  • 1
    This is not a valid json. JSON is a single element - here you two elements, separated by a comma. Add `[` and `]` to make it a list or remove the middle `},{` (leave only a comma) to make it a big dictionary. – h4z3 Aug 06 '19 at 13:41
  • Not a dupe, the other question does not have the `,` separating objects. – Paulo Scardine Aug 06 '19 at 13:42

2 Answers2

3

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"
    }
}]
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
0

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I think this has potential to halt your system if the file is bigger than available RAM (even 1/4 of available RAM if it contains unicode). Also, why not just `"[" + a + "]"`? – Paulo Scardine Aug 06 '19 at 13:51