简体   繁体   English

Python使字符串json可加载

[英]Python Make string json loadable

I have this string: 我有这个字符串:

> x.data
u'{u"orderNumber": u"69898327728", u"resultingTrades": []}'

How can I convert it to json ? 如何将其转换为json This doesn't work: 这不起作用:

> import json
> json.dumps(x.data)
'"{u\\"orderNumber\\": u\\"69898327728\\", u\\"resultingTrades\\": []}"'

It just creates a long string. 它只是创建一个长字符串。 I need to convert it to json so that later I can do json.loads and access the keys in the dict, like this: 我需要将其转换为json,以便以后可以执行json.loads并访问dict中的键,如下所示:

y = json.loads(x.data)["orderNumber"]

The problem I see with your string is that it contains the python u"" format for keys. 我在您的字符串中看到的问题是它包含python u""密钥格式。

Now, if you trust your string and you know it will remain in that format, you can use eval(x.data) to get back a dictionary, but eval is very dangerous. 现在,如果您信任您的字符串并且知道它会保持该格式,则可以使用eval(x.data)来返回字典,但是eval非常危险。

json.loads(json.dumps(eval(a)))

If I were you, I'd put more effort into making sure you get a better string to handle, if that is within your power. 如果我是您,那么我将付出更多的努力来确保您能够更好地处理字符串(如果这是您的能力范围)。

If not, you can try removing the quotes and u manually. 如果没有,您可以尝试手动删除引号和u

data = x.data.replace('u"', "")
data = data.replace('"', "")
json.loads(json.dumps(data))

You can use ast.literal_eval to convert the data to dict : 您可以使用ast.literal_eval将数据转换为dict

>>> import ast
>>> data = u'{u"orderNumber": u"69898327728", u"resultingTrades": []}'
>>> d = ast.literal_eval(data)
>>> d['orderNumber']
u'69898327728'

Then you can use dumps and loads normally: 然后,您可以正常使用dumpsloads

>>> import json
>>> ext = json.dumps(d)
>>> ext
'{"orderNumber": "69898327728", "resultingTrades": []}'
>>> json.loads(ext)['orderNumber']
u'69898327728'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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