1

I now have a string called str1 like this:

{u'price': 542.23, u'name': u'ACME', u'shares': 100}

and I want to transform it into a real JSON data.

the way that uses

data = json.loads(str1)

doesn't work. Do you have any good ideas? (with Python)

4
  • How come did you get a u prefix in your string? Did you do something like: str1 = repr(some_object) ? Commented Apr 27, 2017 at 7:09
  • this is because of Unicode - u Commented Apr 27, 2017 at 7:11
  • @SuperSaiyan the string is like "{u'price': 542.23, u'name': u'ACME', u'shares': 100}" . The whole line is a string. In fact, this string is in a file. And I want to get a JSON data from the file. that's it. Commented Apr 27, 2017 at 7:14
  • Try running eval on that string. It's not json. Commented Apr 27, 2017 at 7:17

1 Answer 1

3
import ast

s = "{u'price': 542.23, u'name': u'ACME', u'shares': 100}"
d = ast.literal_eval(s)

> type(d)
<type 'dict'>

> d['price']
542.23

By the way, eval is not safe.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. If you have Python expressions as an input that you want to evaluate, you shouldn't (have them).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! I search many json topics about this, none of them mentions ast.literal_eval .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.