tags:

views:

45

answers:

2

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 data as a dictionary, so I have:

photos = "jsonFlickrApi({'photos': 'test'})"

# to match {'photos': 'example'}
response_parser = re.compile(r'jsonFlickrApi\((.*?)\)$')
parsed_photos = response_parser.findall(photos)

However, parsed_photos is a list, not a dictionary (according to type(parsed_photos). It outputs like:

["{'photos': 'test'}"]

How can I ensure that my parsed data ends up as a dictionary type?

+1  A: 

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}
Smashery
+1  A: 

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.

Adam Byrtek
Not quite true - you cannot use an eval, as JSON is not compatible with Python literals. Examples: Python uses `None`; JSON uses `null`. Python uses `True`/`False`; JSON uses `true`/`false`
Smashery
@Smashery: It's not a syntactical difference, you just have to define locals for null/true/false and everything will be fine. Not that it's something I'd recommend, just use the libraries.
Adam Byrtek
I've used your first suggestion to get a dictionary - thanks very much! Can you please explain what the [0] in parsed_photos[0] represents?
bfox
@bfox: findAll returns an array of all matches for a given regular expression, [0] takes only the first element.
Adam Byrtek
@Adam Byrtek ah, thanks :)
bfox