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 !

John Doe
  • 9,843
  • 13
  • 42
  • 73
  • That is not a valid json string. The string should be enclosed using " and not ', also the u'' is not valid. Use something like http://jsonlint.com/ to validate. If you use Chrome I would recommend https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa to validate and view json well formatted. – edepe Mar 07 '15 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). – Terry Jan Reedy Mar 07 '15 at 21:22

2 Answers2

3

Unfortunately someone goofed, and that's not JSON.

>>> ast.literal_eval(js)
{'to': 1234, 'message': u'sample message', 'user': 65773722, 'msgId': 28198}
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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)
VelikiiNehochuha
  • 3,775
  • 2
  • 15
  • 32