LizUlloa
LizUlloa

Reputation: 182

raise JSONDecodeError("Extra data", s, end) with json.dump

I need to do a json file with many jsons inside, like: {}{}{}.

I actually can create the file, but when I try to read it, I get this error:

raise JSONDecodeError("Extra data", s, end)
JSONDecodeError: Extra data

Any help?

# Create dictionaries

texto = ['a','b','c','d','e']
keys = ['id','klass','text']
datos = []
for i in range(0,5):
    values = [str(i), str(0), texto[i]]
    dictio = dict(zip(keys, values))
    datos.append(dictio)

# Create the json
for my_dict in datos:
    with open("test.json", 'a') as fp: 
        json.dump(my_dict,fp)

# Read the json:
data = []
with open("test.json") as f: 
    for line in f:
        data.append(json.loads(line))

I expect a .json file with format {}{}{} and read this file in python. Now I have the file with this format, but when I try to read it I have an error

JSONDecodeError("Extra data", s, end)

Upvotes: 4

Views: 6576

Answers (1)

blhsing
blhsing

Reputation: 107124

json.dump does not output a trailing newline character, so after the loop that dumps several JSON strings into the same file there are several JSON objects in the same line, and when you read that line and parse it as with json.loads it will complain about having extra data after the end of the first JSON object.

To fix it you can write a newline character after each call to json.dump. Moreover, there's no need to open the file for each iteration. You can open the file before the loop instead:

with open("test.json", 'w') as fp: 
    for my_dict in datos:
        json.dump(my_dict,fp)
        fp.write('\n')

Upvotes: 4

Related Questions