简体   繁体   中英

how to transform 'JSON-like' string into real JSON data

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)

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).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM