How can JSON data with null value be converted to a dictionary

后端 未结 2 1995
孤独总比滥情好
孤独总比滥情好 2021-01-03 17:42
{
  \"abc\": null,
  \"def\": 9
}

I have JSON data which looks like this. If not for null (without quotes as a string), I could have used ast

2条回答
  •  鱼传尺愫
    2021-01-03 18:19

    You should use the built-in json module, which was designed explicitly for this task:

    >>> import json
    >>> data = '''
    ... {
    ...   "abc": null,
    ...   "def": 9
    ... }
    ... '''
    >>> json.loads(data)
    {'def': 9, 'abc': None}
    >>> type(json.loads(data))
    
    >>>
    

    By the way, you should use this method even if your JSON data contains no null values. While it may work (sometimes), ast.literal_eval was designed to evaluate Python code that is represented as a string. It is simply the wrong tool to work with JSON data.

提交回复
热议问题