Escape double quotes for JSON in Python

前端 未结 4 444
情话喂你
情话喂你 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}
    
    0 讨论(0)
  • 2020-12-03 04:48

    Why not do string suppression with triple quotes:

    >>> s = """my string with "some" double quotes"""
    >>> print s
    my string with "some" double quotes
    
    0 讨论(0)
  • 2020-12-03 05:00

    You should be using the json module. json.dumps(string). It can also serialize other python data types.

    import json
    
    >>> s = 'my string with "double quotes" blablabla'
    
    >>> json.dumps(s)
    <<< '"my string with \\"double quotes\\" blablabla"'
    
    0 讨论(0)
  • 2020-12-03 05:02
    >>> s = 'my string with \\"double quotes\\" blablabla'
    >>> s
    'my string with \\"double quotes\\" blablabla'
    >>> print s
    my string with \"double quotes\" blablabla
    >>> 
    

    When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

    >>> s = """my string with "double quotes" blablabla"""
    'my string with "double quotes" blablabla'
    >>> print s.replace('"', '\\"')
    my string with \"double quotes\" blablabla
    >>> 
    
    0 讨论(0)
提交回复
热议问题