在python中解析JSON时出错

Cep*_*hon 1 python parsing json reddit

我正在尝试解析reddit JSON文件以获取帖子的标题,但是当我使用此代码时:

import urllib2
import json

response = urllib2.urlopen('http://www.reddit.com/r/technology/.json')
data = json.load(response)   
print data['title']
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Traceback (most recent call last):
  File "C:\Users\Harry\Desktop\py\jason.py", line 6, in <module>
    print data['title']
KeyError: 'title'
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,谢谢.

Mar*_*ers 5

该回复没有'title'顶级关键.只有'kind''data'键可以在顶级词典中找到.

你需要仔细看看这里的结构; 该data密钥包含实际的有效负载,但这是没有字典'title'键为好.

这是内容的省略版本:

>>> import pprint
>>> pprint.pprint(data)
{u'data': {u'after': u't3_1wnfuv',
           u'before': None,
           u'children': [{u'data': {u'approved_by': None,
                                    u'author': u'papa00king',
                                    # [...]
                                    # Many keys omitted
                                    # [...]
                                    u'title': u'UK government will unblock websites after adult filter blunder',
                                    u'ups': 1030,
                                    u'url': u'http://www.engadget.com/2014/01/31/uk-government-adult-filter-whitelist/',
                                    u'visited': False},
                          u'kind': u't3'},
                          # [...]
                          # Many many more children
                          # [...]
                          ],
           u'modhash': u''},
 u'kind': u'Listing'}
Run Code Online (Sandbox Code Playgroud)

如果您要查找结果中所有孩子的头衔,请使用:

for child in data['data']['children']:
    print child['data']['title']
Run Code Online (Sandbox Code Playgroud)

换句话说,每个'对象'都有kinddata键,Listing一种对象有一个children键,一个更多的对象列表kinddata键.在t3那种你正在寻找的对象都title在按键data结构.

演示:

>>> for child in data['data']['children']:
...     print child['data']['title']
... 
UK government will unblock websites after adult filter blunder
The upside to being let go by Nokia - Thousands of workers made redundant have set up over 400 new technology companies using grants of up to €20,000 - costing Nokia 'tens of millions of Euro's'
You wouldn't download a car: Honda releases concept car 3D printing files
Could 3D printing provide new solutions for disabled people? - Disabled people often need personalised equipment to help with their individual needs. Could 3D printing provide a cheap and efficient solution?
Five of India's most popular small cars fail their first ever crash tests, showing that they could lead to fatalities or serious injuries if involved in an accident.
Kansas Legislature Wants To Stop Any Other Kansas Cities From Getting Google Fiber
Google’s Latest Moves Toward Scarily Personalized Searches
This $75 synthesizer will turn anything into an instrument
Best Buy slashes price of Surface Pro by $400
This Is What a Computer Sees When It Watches The Matrix
Windows 8.1 update to hide tile interface by default
Young farmers win award for designing cattle management app
IBM's speedy graphene chip could lead to super-efficient mobile devices
South Korea fines Google $196K for illegal data gathering
Microsoft said to be preparing to promote from within, make Satya Nadella next CEO
Pirate Bay ban lifted in Netherlands as blocking torrent sites ruled ‘ineffective’
Haptics, Trackballs and Cheeto Dust: How Valve built the game controller of the future
Icelandic drilling project opens door to volcano-powered electricity
Here's how to know if your Gmail account has been hacked
Amazon considering $20 to $40 price hike for Prime service in US
Massive spending on computing gear underpins Google profits
Yahoo Mail accounts breached, number of affected users not disclosed
AMD (almost) rolls out Mantle, its high performance alternative to Direct3D and OpenGL
Physicists create synthetic magnetic monopole predicted more than 80 years ago
Facebook Is About To Let You Go Anonymous For The First Time
Run Code Online (Sandbox Code Playgroud)