2

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"]
1
  • 2
    What you started with is a Python repr string. You can use ast.literal_eval() to convert it to a dictionary directly. You don't need to go through JSON at all. Commented Feb 1, 2017 at 2:42

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

If given a chance to use eval or ast.literal_eval, I'd go with the latter. It seems a tad safer.
2

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'

Comments

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.