How to parse a string json containing a Python None into json object?
JSON string variable
dummy="{'this':None}"; json.loads(dummy)
Error if I use json.loads
JSONDecodeError: Expecting property name enclosed in double quotes : line 1 and column 2 (char 1)
Next, We replace the single quotes to double quotes.
json.loads(dummy.replace("'", '"'))
Error after replacing single quotes to double quotes
JSONDecodeError: Expecting value: line 1 and column 10 (char 9)
How to parse this json string?
3
Answers
You can make use of
ast.literal_eval
:This is not a JSON. JSON is defined by json.org and RFC8259, and does not recognise single-quoted strings, nor
None
. The JSON equivalent of your data would be{"this":null}
. Fortunately, it is not just garbage, it is in a format of a Python literal, and can be parsed so:Of course, this only works in Python; if you want to interchange this data with other languages, you should use a more standard format (such as e.g. correct JSON).
This works: