Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11541

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? 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:

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

Upvotes: 2

Views: 151

Answers (2)

niemmi
niemmi

Reputation: 17263

You can use ast.literal_eval to convert the data to 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:

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

Upvotes: 2

NuclearPeon
NuclearPeon

Reputation: 6059

The problem I see with your string is that it contains the python u"" format for keys.

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.

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.

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

Upvotes: 2

Related Questions