我很困惑为什么在尝试从 json 文件访问对象数组时必须使用 `.get('key')
req = urllib2.Request("http://website.com/entertainment/entertainment_news.json", None)
opener = urllib2.build_opener()
f = opener.open(req)
stories = json.load(f)
for new_story in stories:
#Why can't I access variables using
new_story.title
#I have to do
new_story.get('title')
请您参考如下方法:
你的问题是,当 json 模块解析一个 JSON 对象时,它返回一个 Python dict - 这是 Python 中更适合手头数据的数据结构.
这意味着您不想尝试访问其上的字段,而是访问 dict 中的项目。用于访问 dict(或类似 dict 的对象)项的 Python 语法是:
dict[name]
所以在你的情况下:
new_story['title']
参见 the documentation for dicts获取更多信息。
dict.get()如果 key 不存在(通常这会产生一个 KeyError),函数允许您轻松获得默认值(默认情况下为 None)。您通常不会想要这种行为(通常最好尽早失败并查看问题出在哪里,而不是获得 None 值,然后在您尝试使用它时出现错误)。
另请注意,这是 with 语句的一个很好的用例,可确保正确关闭连接。由于 urllib2 默认不支持上下文管理器,我们使用 contextlib.closing()做一个:
from contextlib import closing
req = urllib2.Request("http://website.com/entertainment/entertainment_news.json", None)
opener = urllib2.build_opener()
with closing(opener.open(req)) as f:
stories = json.load(f)
...
