0

I've some difficulties to parse a unicode JSON string.

sample:

js = "{'to': 1234, 'message': u'sample message', 'user': 65773722, 'msgId': 28198}"

I want to iterate the JSON object to retrieve the values.

I've already tried, json.dumps, json.loads and js.decode('unicode-escape'), but I keep getting error messages.

Please help..I'm stuck !

Many thanks !

2
  • That is not a valid json string. The string should be enclosed using " and not ', also the u'' is not valid. Use something like jsonlint.com to validate. If you use Chrome I would recommend chrome.google.com/webstore/detail/json-formatter/… to validate and view json well formatted. Commented Mar 7, 2015 at 18:14
  • js is not a unicode string, but a bytestring that happens to contain a unicode literal. It is not clear whether you are trying to construct a valid json string, or whether you are trying to parse a string that someone else gave you (that only pretends to be valid json). Commented Mar 7, 2015 at 21:22

2 Answers 2

3

Unfortunately someone goofed, and that's not JSON.

>>> ast.literal_eval(js)
{'to': 1234, 'message': u'sample message', 'user': 65773722, 'msgId': 28198}
Sign up to request clarification or add additional context in comments.

6 Comments

@Ignaciao; I do not understand what you mean. Please explain !
String not JSON. JSON functions not work. Find other way to parse.
Treat it as a dictionary maybe ?
It's a string. It needs to be parsed before you can access it.
It is JSON, the u at the beginning of the string shows that it's encoded in unicode see here
|
1

it is not valid json

s = "{'to': 1234, 'message': u'sample message', 'user': 65773722, 'msgId': 28198}"
valid = s.replace("u'", "'")
supervalid = v.replace("'", '"')
json.loads(super_valid)

2 Comments

I'am convinced (except for the errors in the variables) ;-))
Yes =), valid = s.replace("u'", "'"); supervalid = valid.replace("'", '"'); json.loads(supervalid)

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.