0

I'm quite new to python and im trying to get a JSON file to be created and then loaded and then organised. But I keep getting a weird error.

This is my code to write the file:

def save(): # save to file
    with open(class_name, 'a') as f:
        data = [name, score]
        json.dump(data, f)

This is my code to load the file:

with open(class_name, 'r') as f:
            data2 = json.load(f)

This is my code to organise the file:

with open(class_name, 'r') as f:
            data2 = json.load(f)
            Alpha = sorted(data, key=str.lower)
        print(Alpha)

And this is my error:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    viewscores()
  File "C:\Users\Danny\Desktop\Task123.py", line 60, in viewscores
    data2 = json.load(f)
  File "C:\Python34\lib\json\__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Python34\lib\json\__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "C:\Python34\lib\json\decoder.py", line 346, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 13 - line 1 column 153 (char 12 - 152)

1 Answers1

0

You are appending data to your file, creating multiple JSON documents in that file. The json.load() command on the other hand can only load one JSON document from a file, and is now complaining you have more data after the JSON document.

Either adjust your code to load those documents separately (insert newlines after each entry you append, and load the JSON documents line by line, or replace everything in the file with a new JSON object.

Using newlines as separators, then loading all the entries separately would look like:

def save(): # save to file
    with open(class_name, 'a') as f:
        data = [name, score]
        json.dump(data, f)
        f.write('\n')

and loading would be:

with open(class_name, 'r') as f:
    scores = []
    for line in f:
        entry = json.loads(line)
        scores.append(entry)

after which you could sort those entries if you so wish.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343