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]]}]
This works but doesn't seem too elegant
import json
json.dumps(json.JSONDecoder().decode(str_w_quotes))
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]]}]
>>> "[{\"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}]"
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.