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:
JavaScript
x
3
1
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}'
2
y = json.loads(x)
3
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
JavaScript
1
3
1
x = '{"level": 1, "body": "hey", "track": 199}'
2
y = json.loads(x) # this does work but how do I split the string to these phrases?
3
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.
JavaScript
1
2
1
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}]'
2
When you load this, you’ll get a list of dictionaries.