How do I put a dictionary into JSON without the escape slash

11,044

The reason is because you are dumping your JSON data twice. Once outside the function and another inside it. For reference:

>>> import json    
>>> data = {'number':7, 'second_number':44}

# JSON dumped once, without `\`
>>> json.dumps(data)
'{"second_number": 44, "number": 7}'

# JSON dumped twice, with `\`
>>> json.dumps(json.dumps(data))
'"{\\"second_number\\": 44, \\"number\\": 7}"'

If you print the data dumped twice, you will see what you are getting currently, i.e:

>>> print json.dumps(json.dumps(data))
"{\"second_number\": 44, \"number\": 7}"
Share:
11,044
Scott Binkley
Author by

Scott Binkley

Updated on June 05, 2022

Comments

  • Scott Binkley
    Scott Binkley almost 2 years

    I'm not sure what I am doing wrong. I have a dictionary that I want to convert to JSON. My problem is with the escape \

    How do I put a dictionary into JSON without the escape \

    Here is my code:

    def printJSON(dump):
        print(json.dumps(dump, indent=4, sort_keys=True))
    
    data = {'number':7, 'second_number':44}
    json_data = json.dumps(data)
    printJSON(json_data)
    

    The output is: "{\"second_number\": 44, \"number\": 7}"

    I want the output to look like this: "{"second_number": 44, "number": 7}"

  • Scott Binkley
    Scott Binkley over 7 years
    Yup that was the problem. I suppose that is what to expect when hacking around