Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Unicode Object to Python Dict

A request object that I'm dealing with has the following value for the key "address":

  u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}"

I need to operate on this unicode object as a dictionary. Unfortunately, json.loads() fails because it is not a json compatible object.

Is there any way to deal with this? Do I have to work with the the json.JSONDecoder object?

like image 907
Ben Avatar asked Sep 27 '11 18:09

Ben


People also ask

How to convert Unicode to json in Python?

Use json. dumps() to serialize a Unicode string into JSON Call json. dumps(unicode, ensure_ascii=False) to serialize the string unicode into a JSON string. ensure_ascii=False ensures that Unicode characters are not encoded as Unicode escape sequences in the resulting string.

How do you change a Unicode to a string in Python?

Use str. encode() to convert a Unicode string to an ASCII string. Call str. encode(encoding, errors) with encoding as "ASCII" and errors as "ignore" to return an ASCII representation of a Unicode string str .


1 Answers

>>> ast.literal_eval(u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}")
{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}
like image 77
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 23:11

Ignacio Vazquez-Abrams