使用Python解析JSON文件

翻译自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







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值