Delremm
Delremm

Reputation: 3161

python json dumps

i have the following string, need to turn it into a list without u'':

my_str = "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"

i can get rid of " by using

import ast
str_w_quotes = ast.literal_eval(my_str)

then i do:

import json
json.dumps(str_w_quotes)

and get

[{\"id\": 2, \"name\": \"squats\", \"wrs\": [[\"55\", 9]]}]

Is there a way to get rid of backslashes? the goal is:

[{"id": 2, "name": "squats", "wrs": [["55", 9]]}]

Upvotes: 32

Views: 84921

Answers (6)

Ajay Tom George
Ajay Tom George

Reputation: 2279

{"result": "{\\"id\\": 5, \\"macaddr\\": \\"00:11:11:xx:11:D3\\", \\"ip\\": \\"10.46.02.313\\"}'

If anybody is getting results like this with \\, check if you have called json.dump twice on the same output. For me that was the case

Upvotes: 2

Michael
Michael

Reputation: 88

Here's something I was working on.

Before I had the return statement as json.dumps(value) and had the \ issue you're facing. But as the string is already json as yours is, adding this seems to be pointless. I returned the value and bingo 's gone away.

As for your other requirements I don't know but the \ issue can be fixed like this.

    def get(self):
        CPU = psutil.cpu_percent(interval=10, percpu=False)
        CORECOUNT = psutil.cpu_count(logical=False)
        THREADCOUNT = psutil.cpu_count()
        value = {
        "CPU": CPU,
        "CPU_Cores": CORECOUNT,
        "CPU_Threads": THREADCOUNT,
        }
        return value

Upvotes: 0

Shruti Kar
Shruti Kar

Reputation: 147

You don't dump your string as JSON, rather you load your string as JSON.

import json
json.loads(str_w_quotes)

Your string is already in JSON format. You do not want to dump it as JSON again.

Upvotes: 9

slohr
slohr

Reputation: 623

This works but doesn't seem too elegant

import json
json.dumps(json.JSONDecoder().decode(str_w_quotes))

Upvotes: 21

Alex Spencer
Alex Spencer

Reputation: 862

json.dumps thinks that the " is part of a the string, not part of the json formatting.

import json
json.dumps(json.load(str_w_quotes))

should give you:

 [{"id": 2, "name": "squats", "wrs": [["55", 9]]}]

Upvotes: 16

vikki
vikki

Reputation: 2814

>>> "[{\"id\": 2, \"name\": \"squats\", \"wrs\": [[\"55\", 9]]}]".replace('\\"',"\"")
'[{"id": 2, "name": "squats", "wrs": [["55", 9]]}]'

note that you could just do this on the original string

>>> "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]".replace("u\'","\'")
"[{'name': 'squats', 'wrs': [['99', 8]], 'id': 2}]"

Upvotes: 6

Related Questions