[Python] How to create json content object where some of the content will be prefixed and...

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página