1

I have a string with utf-8 encoding, like

>>> print s
"{u'name':u'Pradip Das'}"

Basically I load some data from JSON file and it loads as above. Now, I want to covert this string in to python dictionary. So I can do like:

>>> print d['name']
'Pradip Das'
Pradip Das
  • 728
  • 1
  • 7
  • 16
  • 1
    See the link posted by Dmitry Grigoryev... you can import json and use json.load() rather than reading the JSON-formatted string. – THK Nov 17 '15 at 10:41

2 Answers2

4

Use EVAL to convert string to dictionary.

d=eval(s)
print d['name']

Let me know if there are any batter way to do so.

Pradip Das
  • 728
  • 1
  • 7
  • 16
4

You can use the built-in ast.literal_eval:

>>> import ast
>>> a = ast.literal_eval("{'a' : '1', 'b' : '2'}")
>>> a
{'a': '1', 'b': '2'}
>>> type(a)
<type 'dict'>

This is safer than using eval. As the docs itself recommends it:

>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.

Additionally, you can read this article which will explain why you should avoid using eval.

JRodDynamite
  • 12,325
  • 5
  • 43
  • 63