28

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]]}]
Delremm
  • 3,071
  • 4
  • 17
  • 13
  • 3
    `json.dumps` returns `'[{"id": 2, "name": "squats", "wrs": [["99", 8]]}]'` for me. – Janne Karila Mar 07 '13 at 13:37
  • 2
    Are you sure you are seeing backslashes and not just escaped quotes? For example `"\""` is the same as `'"'`. – Janne Karila Mar 07 '13 at 13:39
  • The `u` just indicates it's a unicode string in python < 3.0. Are you sure you want to convert to simple strings? – Tim Mar 07 '13 at 13:39
  • 1
    You don't get rid of `"`, you're evaluating the string and returning a _list_. `str_w_quotes` is a terrible name for a list – John La Rooy Mar 07 '13 at 13:40
  • seems like you are passing `my_str` to json.dumps otherwise `str_w_quotes` comes out without the `u`s like JanneKarila says. – vikki Mar 07 '13 at 13:46
  • i had similar results when i unintentionally double-dumped string, like `json.dumps(json.dumps(str))` , check you don't do that guys – Alexandr Perfilov Jul 22 '15 at 18:44

4 Answers4

19

This works but doesn't seem too elegant

import json
json.dumps(json.JSONDecoder().decode(str_w_quotes))
slohr
  • 573
  • 5
  • 9
13

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]]}]
Alex Spencer
  • 794
  • 1
  • 11
  • 22
9

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.

Marcello B.
  • 3,822
  • 10
  • 45
  • 61
Shruti Kar
  • 147
  • 1
  • 11
6
>>> "[{\"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}]"
vikki
  • 2,736
  • 1
  • 18
  • 25