Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}"

like image 813
Scott Binkley Avatar asked Nov 29 '16 19:11

Scott Binkley


People also ask

How do I remove backslash from JSON dumps?

Using replace() Function Along with The json. Loads() Function to Remove Backslash from Json String in Python.

Can JSON have a dictionary?

JSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists. Here is a simple example with just 4 attribute/value pairs.

Does JSON dump escape quotes?

Furthermore, all double quotes of the actual JSON formatting are escaped with a backslash.

How do I add a forward slash in JSON?

Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out: This is because HTML does not allow a string inside a <script> tag to contain </ , so in case that substring's there, you should escape every forward slash. Save this answer.


1 Answers

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}"
like image 166
Moinuddin Quadri Avatar answered Sep 28 '22 03:09

Moinuddin Quadri