saurabh
saurabh

Reputation: 303

How to convert a unicode string in a dictionary

I have a unicode string after applying json.loads() through which I got

u"{'1':2, '3':2}"

Now how do I convert it in a dictionary like

{'1':2, '3':2}

I have tried using

re.sub

but still couldn't find anything.

Upvotes: 0

Views: 1072

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121634

Use ast.literal_eval():

import ast

dictionary_object = ast.literal_eval(stringobj)

This supports strings, numbers, dictionaries, lists, tuples and sets, but won't execute any other Python code (so there is no executable code risk here).

Demo:

>>> import ast
>>> ast.literal_eval(u"{'1':2, '3':2}")
{'1': 2, '3': 2}

However, most likely you should not have encoded the value like that in the first place. It looks as if you did:

obj = {'1': 2, '3': 2}
json.encode(str(obj))

instead of

obj = {'1': 2, '3': 2}
json.encode(obj)

The latter produces a proper JSON object, the former a JSON string containing the representation of a Python dictionary.

Upvotes: 3

Related Questions