vaibhav1312 vaibhav1312 - 11 months ago 55
Python Question

Converting a String into Dictionary python

I want to have a dictionary from

>>> page_detail_string = urllib2.urlopen("").read()

It returns a string like

>>> page_detail_string
'{"about":"Ideas for development of India","category":"Community","description":"Platform where you can discuss and share your ideas which you think might help in betterment of our country.\\nPlease respect other community members and do not talk politics here.","is_published":true,"talking_about_count":0,"username":"Ideas4India","were_here_count":0,"id":"250014455083430","name":"Ideas 4 India","link":"http:\\/\\/\\/Ideas4India","likes":23}'

Now i want to convert it to dictionary which i can be easily done by using ast.literal_eval

>>> import ast
>>> dict_page = ast.literal_eval(page_detail_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/", line 63, in _convert
in zip(node.keys, node.values))
File "/usr/lib/python2.7/", line 62, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/usr/lib/python2.7/", line 79, in _convert
raise ValueError('malformed string')

but I think it throws this error because of


Is there any way i can convert it to dictionary by stripping above key and value ("is_published":true).


Answer Source

What you get is a json string, you shoule use json.loads to convert to dict

import json