Invalid control character with Python json.loads

The control character can be allowed inside a string as follows,

json_str = json.loads(jsonString, strict=False)

You can find this in the docs for python 2, or the docs for python 3

If strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.


try to use "strict=False" in json.loads , it will ignore "\n" and another Control characters. like the follwing:

import json
  
test_string = ' { "key1" : "1015391654687" , "key2": "value2 \n " } '

res = json.loads(test_string, strict=False)
  
print(res)

output :

{'key1': '1015391654687', 'key2': 'value2 \n '}

There is no error in your json text.

You can get the error if you copy-paste the string into your Python source code as a string literal. In that case \n is interpreted as a single character (newline). You can fix it by using raw-string literals instead (r'', Use triple-quotes r'''..''' to avoid escaping "' quotes inside the string literal).

Tags:

Python

Json