Skip to content Skip to sidebar Skip to footer

How Can I Ensure That My Python Regular Expression Outputs A Dictionary?

I'm using Beej's Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this: jsonFlickrApi({'photos': 'example'}) I want to access the returned d

Solution 1:

You need to use a JSON parser to convert the string representation to actual Python data structure. Take a look at the documentation of the json module in the standard library for some examples.

In other words you'd have to add the following line at the end of your code

photos = json.loads(parsed_photos[0])

PS. In theory you could also use eval to achieve the same effect, as JSON is (almost) compatible with Python literals, but doing that would open a huge security hole. Just to let you know.


Solution 2:

If you're using Python 2.6, you can just use the JSON module to parse JSON stuff.

import json
json.loads(dictString)

If you're using an earlier version of Python, you can download the simplejson module and use that.

Example:

>>> json.loads('{"hello" : 4}')
{u'hello': 4}

Post a Comment for "How Can I Ensure That My Python Regular Expression Outputs A Dictionary?"