Escape double quotes for JSON in Python

前端 未结 4 576
情话喂你
情话喂你 2020-12-03 04:04

How can I replace double quotes with a backslash and double quotes in Python?

>>> s = \'my string with \"double quotes\" blablabla\'
>>>          


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 04:45

    Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:

    >>> a = {'x':1}
    >>> b = json.dumps(json.dumps(a))
    >>> b
    '"{\\"x\\": 1}"'
    >>> json.loads(json.loads(b))
    {u'x': 1}
    

提交回复
热议问题