Patrick Burns
Patrick Burns

Reputation: 1833

decode encoded JSON result in python

I have JSON result

{"sUrlRedirect":"http://dez.loc/registration","sMsgTitle":null,"sMsg":"\u041f\u043e\u0437\u0434\u0440\u0430\u0432\u043b\u044f\u0435\u043c! \u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u043e\u0448\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e","bStateError":false}

How i can decode it in python. Results must be such like this

{"sUrlRedirect":"http://dez.loc/registration","sMsgTitle":null,"sMsg":"Поздравляем! Регистрация прошла успешно","bStateError":false}

Thanks...

UPD

Can i do this without using json module?

Upvotes: 1

Views: 1436

Answers (2)

root
root

Reputation: 80346

Use the json module:

In [1]: import json

In [2]: s = '''{"sUrlRedirect":"http://dez.loc/registration","sMsgTitle":null,"sMsg":"\u041f\u043e\u0437\u0434\u0440\u0430\u0432\u043b\u044f\u0435\u043c! \u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u043e\u0448\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e","bStateError":false}'''

In [3]: json.loads(s)
Out[3]: 
{u'bStateError': False,
 u'sMsg': u'\u041f\u043e\u0437\u0434\u0440\u0430\u0432\u043b\u044f\u0435\u043c! \u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u043e\u0448\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e',
 u'sMsgTitle': None,
 u'sUrlRedirect': u'http://dez.loc/registration'}

In [4]: for k, v in json.loads(s).iteritems():
            print k, v
   ...:     
sMsgTitle None
bStateError False
sMsg Поздравляем! Регистрация прошла успешно
sUrlRedirect http://dez.loc/registration

In [5]: print repr(json.loads(s)).decode("unicode-escape")
{u'sMsgTitle': None, u'bStateError': False, u'sMsg': u'Поздравляем! Регистрация прошла успешно', u'sUrlRedirect': u'http://dez.loc/registration'}

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43235

Just use inbuilt python json module to load the json as python object, you will however see that your unicode strings are represented as '\u041f' , when you use them in your application, it should appear fine as Russian text.

>>> json_str= '{"sUrlRedirect":"http://dez.loc/registration","sMsgTitle":null,"sMsg":"\u041f\u043e\u0437\u0434\u0440\u0430\u0432\u043b\u044f\u0435\u043c! \u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u043e\u0448\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e","bStateError":false}'
>>> import json
>>> the_dict = json.loads(json_str)
>>> the_dict
{u'sMsgTitle': None, u'bStateError': False, u'sMsg': u'\u041f\u043e\u0437\u0434\u0440\u0430\u0432\u043b\u044f\u0435\u043c! \u0420\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044f \u043f\u0440\u043e\u0448\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e', u'sUrlRedirect': u'http://dez.loc/registration'}

>>> print the_dict['sMsg']
Поздравляем! Регистрация прошла успешно

Upvotes: 4

Related Questions