json.decoder.JSONDecodeError: Invalid control character at

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Check out my new book

json.decoder.JSONDecodeError: Invalid control character at #

The Python "json.decoder.JSONDecodeError: Invalid control character at" is caused when we try to parse a JSON string that contains control characters without setting strict to False. To solve the error, set the strict keyword argument to False in the call to json.loads().

Here is an example of how the error occurs.

main.py
import json my_json_str = '{"name": "Alice Smith}' # ⛔️ json.decoder.JSONDecodeError: Invalid control character at: line 1 column 17 (char 16) result = json.loads(my_json_str)

Notice that we have a missing double quote at the end of the value.

To solve the error, make sure you don't have any missing closing quotes in your JSON string and set the strict keyword argument to False.

main.py
import json my_json_str = '{"name": "Alice Smith"}' # 👇️ set strict to False result = json.loads(my_json_str, strict=False) print(result) # 👉️ {'name': 'Alice Smith'}

If strict is set to False, then control characters are allowed inside strings.

Control characters are those with character codes in the 0-31 range, e.g. \t, \n, \r, \0, etc.

By default, strict is set to True, so no control characters are allowed in the JSON string.

You have to make sure the JSON data you are trying to parse is valid.

The fastest way to validate and correct your JSON is to use a JSON validator.

Paste your payload into the form, the validator checks for errors and sometimes directly fixes them.

If you got the error when copy-pasting a JSON string in your Python code, prefix the JSON string with r to mark it as a raw string.

main.py
my_json_str = r'{"name": "Alice Smith"}'

You can also set the strict keyword argument to False when using the json.load() method to read from a JSON file.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f, strict=False) print(my_data) # 👉️ {'name': 'Alice', 'age': 30}

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

Use the search field on my Home Page to filter through my more than 3,000 articles.