【发布时间】:2014-01-29 16:00:02
【问题描述】:
我不断收到 KeyError: 'message' 但我不知道为什么?
这是我正在解析的数据示例:
{
"data": [
{
"id": "86264418970_10152060349923971",
"from": {
"category": "Health/beauty",
"category_list": [
{
"id": "181045748599578",
"name": "Personal Trainer"
}
],
"name": "Infinite Fitness - Personal Training",
"id": "86264418970"
},
"to": {
"data": [
{
"category": "Kitchen/cooking",
"category_list": [
{
"id": "132852590115660",
"name": "Kitchen Supplies"
},
{
"id": "150060378385891",
"name": "Appliances"
}
],
"name": "Vitamix",
"id": "89031985873"
}
]
},
"message": "Favourite Things Friday! \nThis a new feature for 2014. Every Friday will feature a product, business, person, quote, etc that is our absolute favourite!! If you have ideas or want to share your favourite thing, let us know.\n\nThis week, it's the Vitamix! Honestly it's the one kitchen appliance that I just can't live without. Although shakes are nothing new in our world, the degree to which the Vitamix blends is incomparable to anything I've seen. It has made adding a variety of veggies (broccoli, spinach, kale, beets, carrots) a breeze as it blends to a completely smooth consistency. \n\nBonus points, the kids LOVE the shakes and little do they know all the amazing things they're getting with it. \nExtra bonus points, although I don't do it often, I have made soup and ice cream with it. Super easy.\nExtra extra bonus points, clean up is a snap! Less than a minute, no joke.\n\n(The favourite things feature is my own opinion and although I gush, I am not being paid to do so)",
"message_tags": {
"245": [
{
"id": "89031985873",
"name": "Vitamix",
"type": "page",
"offset": 245,
"length": 7
}
]
},
"privacy": {
"value": ""
},
"type": "status",
"application": {
"name": "Pages Manager for iOS",
"namespace": "fbpagemanager_ios",
"id": "165907476854626"
},
"created_time": "2014-01-10T15:01:41+0000",
"updated_time": "2014-01-10T15:01:41+0000"
},
{
"id": "7568536355_10102570693591239",
"from": {
"category": "Computers/internet website",
"name": "Lifehacker",
"id": "7568536355"
下面是我的代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
import json
import urllib
import sys
import time
import re
class FacebookSearch(object):
def __init__(self):
self.url_format = 'https://graph.facebook.com/search?{query}&{type}&{access_token}'
self.access_token = 'access_token=XXXXXXXXX|XXXXXXX'
def make_search_url(self, q, type='post', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
url = self.url_format.format(query=query, type=type,
access_token=self.access_token, **queryargs)
return url
def search(self, q, type='post', **queryargs):
url = self.make_search_url(q, **queryargs)
page = urllib.urlopen(url)
return page.read()
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = FacebookSearch()
data = ts.search('appliance')
js = json.loads(data)
messages = ([msg['created_time'].replace('T', ' ').replace('+0000', ''), msg['message'].replace('\n', ' ').encode('utf8'), msg['from']['id']] for msg in js.get('data', []))
write_csv('fb_washerdryer.csv', messages, append=True)
if __name__ == '__main__':
main()
这是错误的完整追溯:
[ec2-user@ip-172-31-46-164 ~]$ ./facebook_washer_dryer4.sh Traceback (最近一次通话最后):文件“./facebook_washer_dryer4.sh”,行 47,在 main() 文件“./facebook_washer_dryer4.sh”,第 44 行,在 main write_csv('fb_washerdryer.csv', messages, append=True) 文件“./facebook_washer_dryer4.sh”,第 35 行,在 write_csv out_csv.writerows(rows) 文件“./facebook_washer_dryer4.sh”,第 42 行,在 messages = ([msg['created_time'].replace('T', '').replace('+0000', ''), msg['message'].replace('\n', ' ').encode('utf8'), msg['from']['id']] for msg in js.get('data', [])) KeyError: '消息' [ec2-user@ip-172-31-46-164 ~]$
我已经查看了我正在解析一侧并返回另一侧的 json,但我不明白为什么会收到“键值错误”。
我已经尝试解决这个问题 2 天了,并且真的很想找到一个解决方案。任何帮助或建议将不胜感激
【问题讨论】:
-
之后尝试将
msg['message']替换为msg.get('message', 'Key "message" is not present.')和printmessages`。可能并非数据中的所有消息都包含message键。 -
这完全有效!非常感谢乔尔。我只会在我的代码运行的 1/2 处得到错误。我无法弄清楚为什么它有时会出错而不是其他人。我什至从没想过消息密钥可能不在所有消息上。非常感谢您的见解
-
没问题。很高兴它起作用了:)