I’m trying to print every value of a Json using Python. There are 3 Json phrases that are seperated by “,” and I get an error if I try to load all of it to the json.loads function.
Here is what I’m trying to do:
x = '{"level": 1, "body": "hey", "track": 199}, {"level": 2, "body": "good", "track": 199}, {"level": 3, "body": "nice", "track": 199}, {"level": 4, "body": "thin", "track": 199}' y = json.loads(x)
and the error I’m getting:
json.decoder.JSONDecodeError: Extra data: line 1 column 55 (char 54)
The only way I got it to work is take every json phrase in that string and use the json.loads() function on it.
so
x = '{"level": 1, "body": "hey", "track": 199}' y = json.loads(x) # this does work but how do I split the string to these phrases?
Advertisement
Answer
The top level of a JSON string must be just one array or object. If you want to have multiple objects, they must be in an array.
x = '[{"level": 1, "body": "hey", "track": 199}, {"level": 2, "body": "good", "track": 199}, {"level": 3, "body": "nice", "track": 199}, {"level": 4, "body": "thin", "track": 199}]'
When you load this, you’ll get a list of dictionaries.