skip to Main Content

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


  1. You can make use of ast.literal_eval:

    >>> import ast
    >>> ast.literal_eval("{'this':None}")
    {'this': None}
    
    Login or Signup to reply.
  2. 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:

    from ast import literal_eval
    
    obj = literal_eval("{'this':None}")
    

    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).

    Login or Signup to reply.
  3. This works:

    dummy = ‘{"this": null}’; json_obj = json.loads(dummy)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search