[英]how to transform 'JSON-like' string into real JSON data
I now have a string called str1 like this: 我现在有一个名为str1的字符串,如下所示:
{u'price': 542.23, u'name': u'ACME', u'shares': 100}
and I want to transform it into a real JSON data. 我想将其转换为真正的JSON数据。
the way that uses 使用的方式
data = json.loads(str1)
doesn't work. 不起作用。 Do you have any good ideas?
你有什么好主意吗? (with Python)
(使用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. 顺便说一下,eval并不安全。
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. 如果输入不是有效的Python数据类型,ast.literal_eval会引发异常,因此如果不是,则不会执行代码。
Use ast.literal_eval whenever you need eval. 无论何时需要eval,都要使用ast.literal_eval。 If you have Python expressions as an input that you want to evaluate, you shouldn't (have them).
如果您将Python表达式作为要评估的输入,则不应该(拥有它们)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.