pythonreplace

How to create json content object where some of the content will be prefixed and suffixed with backslash and doublequote \"


I have following python code:

import json

data = {"name": "John", "age": 30, "city": "New York"}
print(data)
json_string = json.dumps(data, indent=4)
print(json_string)
json_string_escaped = json_string.replace('"','\\"')
print(json_string_escaped)
dataone = {"json_string": json_string_escaped}
print(dataone)

now json_string_escaped is good as showing:

{
    \"name\": \"John\",
    \"age\": 30,
    \"city\": \"New York\"
}

now I need to attach this escaped string to new JSON. The format of single backslash and double quote is required by the REST API:

dataone = {"json_string": json_string_escaped}
print(dataone)

But that added another backslash which is not intended behavior:

{'json_string': '{\n    \\"name\\": \\"John\\",\n    \\"age\\": 30,\n    \\"city\\": \\"New York\\"\n}'}

How to have dataone variable with single backslash and doublequote?


Solution

  • Don't do your own escaping, let json.dumps() do it for you. To get the nested escaping you want, use multiple layers of json.dumps().

    data = {"name": "John", "age": 30, "city": "New York"}
    dataone = json.dumps({"json_string": json.dumps(data)})
    print(dataone)
    

    output:

    {"json_string": "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"}