开发者

How can I ensure that my Python regular expression outputs a dictionary?

开发者 https://www.devze.com 2023-01-20 13:37 出处:网络
I\'m using Beej\'s Python Flickr API to ask Flickr for JSON. The unparsed string Flickr returns looks like this:

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'jsonFli开发者_如何学PythonckrApi\((.*?)\)$')
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?


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}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消