python json dumps

Question:

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]]}]
Asked By: Delremm

||

Answers:

>>> "[{"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}]"
Answered By: vikki

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]]}]
Answered By: Alex Spencer

This works but doesn’t seem too elegant

import json
json.dumps(json.JSONDecoder().decode(str_w_quotes))
Answered By: slohr

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.

Answered By: Shruti Kar

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
Answered By: Michael
{"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

Answered By: Ajay Tom George
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.