Borislav Hadzhiev
Last updated: Apr 24, 2022
Photo from Unsplash
The Python "json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1" occurs when we try to parse an invalid JSON string. To solve the error, make sure to escape any double quotes with two backslashes and correct any other errors in the JSON string.
Here is an example of how the error occurs.
import json # ⛔️ json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 31 (char 30) data = json.loads( '{ "employee":{ "name":"Alice \"developer\"" } }' ) # 👆️ did not escape JSON str correctly
Notice that the value of the name
key contains double quotes.
If you have double quotes in the string, make sure to escape them using two backslashes.
import json data = json.loads( '{ "employee":{ "name":"Alice \\"developer\\"" } }' ) print(data) # 👉️ {'employee': {'name': 'Alice "developer"'}}
Alternatively, you can prefix the string with r
to indicate that it's a raw
string.
import json data = json.loads( r'{ "employee":{ "name":"Alice \"developer\"" } }' ) print(data) # 👉️ {'employee': {'name': 'Alice "developer"'}}
The error is also caused if we have any syntax errors in the JSON string.
Here is an example of a syntax error due to using colons in a JSON array.
import json # ⛔️ json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 8 (char 7) data = json.loads( '["name": "Alice", "age": 30]' )
If you meant to declare a JSON array, make sure to separate its elements with a comma.
import json data = json.loads( '["name", "Alice", "age", 30]' ) print(data) # 👉️ ['name', 'Alice', 'age', 30]
If you meant to declare a set of key-value pairs, wrap them in curly braces.
import json data = json.loads( '{"name": "Alice", "age": 30}' ) print(data) # 👉️ {'name': 'Alice', 'age': 30}
The fastest way to validate and correct your JSON is to use a JSON validator.
If you are making an HTTP request and getting invalid JSON data, you have to fix the issue on the backend.
Here is an example of a more complex JSON string.
import json data = json.loads( """ [ {"id": 1, "name": "Alice", "is_subscribed": true}, {"id": 2, "name": "Bob", "is_subscribed": false}, {"id": 3, "name": "Carl", "is_subscribed": true, "address": {"country": "Canada"}} ] """ ) # 👇️ [{'id': 1, 'name': 'Alice', 'is_subscribed': True}, {'id': 2, 'name': 'Bob', 'is_subscribed': False}, {'id': 3, 'name': 'Carl', 'is_subscribed': True, 'address': {'country': 'Canada'}}] print(data)