您的位置:首页 > 编程语言 > Python开发

使用Python解析JSON文件

2014-11-14 01:17 681 查看
翻译自https://developer.yahoo.com/python/python-json.html

许多Yahoo!的web服务不仅提供XML数据,也提供JSON格式的数据。JSON数据结构能够直接映射到Python的数据类型里,所以使用Python获取JSON数据很方便很强大,而获取XML数据还需要写解析XML的Python代码。


Python的JSON库

Python中有几个JSON库,但是最流行的是simplejson。从这儿下载:https://pypi.python.org/pypi/simplejson

例子:搜索web

import simplejson, urllib
APP_ID = 'YahooDemo' # Change this to your API key
SEARCH_BASE = 'http://search.yahooapis.com/ WebSearchService/V1/webSearch'

class YahooSearchError(Exception):
    pass

def search(query, results=20, start=1, **kwargs):
    kwargs.update({
        'appid': APP_ID,
        'query': query,
        'results': results,
        'start': start,
        'output': 'json'
    })
    url = SEARCH_BASE + '?' + urllib.urlencode(kwargs)
    result = simplejson.load(urllib.urlopen(url))
    if 'Error' in result:
        # An error occurred; raise an exception
        raise YahooSearchError, result['Error']
    return result['ResultSet']
利用上面的代码:

>>> info = search('json python')
>>> info['totalResultsReturned']
20
>>> info['totalResultsAvailable']
u'212000'
>>> info['firstResultPosition']
1
>>> results = info['Result']
>>> for result in results:
...     print result['Title'], result['Url']
Python Stuff http://undefined.org/python/ SourceForge.net: json-py https://sourceforge.net/projects/json- py
Introducing JSON http://www.json.org/ ...
Each result is a Python dictionary containing a number of keys. The full
dictionary for a result looks like this:

每一个result是一个Python dictionary类型的数据,一个result的整个dictionary的数据类似于下:

>>> from pprint import pprint
>>> pprint(results[0])
{u'Cache': {u'Size': u'22237',
            u'Url': u'http://216.109.125.130/search/cache... '},
 u'ClickUrl': u'http://undefined.org/python/#simple_ json',
 u'DisplayUrl': u'undefined.org/python/#simple_json',
 u'MimeType': u'text/html',
 u'ModificationDate': 1150786800,
 u'Summary': u'... Python Stuff. Support the development of py2app, xattr ...',
 u'Title': u'Python Stuff',
 u'Url': u'http://undefined.org/python/#simple_ json'}


search()函数接受一个关键字参数,这个参数转换成请求字符串传给API端。下面是请求 developer.yahoo.com站点的例子:

info = search('python', site='developer.yahoo.com')


下面是如何搜索PowerPoint 文件:

info = search('python', format='ppt')


返回的更多信息查看 in
the API documentation.https://developer.yahoo.com/search/web/V1/webSearch.html#responsetable
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: