2014-01-10 130 views
0

我不断收到KeyError:'message',我不知道为什么?JSON键值错误混淆

这里是一个数据我解析的样本:

{

"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() 

以下是完整的追溯错误:

[[email protected] ~]$ ./facebook_washer_dryer4.sh Traceback (most recent call last): File "./facebook_washer_dryer4.sh", line 47, in main() File "./facebook_washer_dryer4.sh", line 44, in main write_csv('fb_washerdryer.csv', messages, append=True) File "./facebook_washer_dryer4.sh", line 35, in write_csv out_csv.writerows(rows) File "./facebook_washer_dryer4.sh", line 42, in messages = ([msg['created_time'].replace('T', ' ').replace('+0000', ''), msg['message'].replace('\n', ' ').encode('utf8'), msg['from']['id']] for msg in js.get('data', [])) KeyError: 'message' [[email protected] ~]$

我已经回顾了json解析一边和另一边,我不明白为什么我会得到一个“键值错误”。

我一直在试图找出这2天现在,并真的想发现一个解决方案。任何帮助或建议将不胜感激

+0

尝试用'msg.get('message','Key'消息'不存在')''''''''''''''''后面的'print'messages'替换'msg ['message']''。数据中并非所有消息都可能包含“消息”密钥。 –

+0

完全工作!非常感谢Joel。我只会得到我的代码运行的一半的错误。我无法弄清楚为什么有时会出错,而不是其他人。我甚至从未想过消息密钥可能不在所有消息上。真的很感谢洞察 – user2748540

+0

没问题。很高兴它工作:) –

回答

2

尝试替换msg['message']msg.get('message', 'Key "message" is not present.')和打印messages事后。

有可能数据中的所有消息都不包含消息密钥。使用get()将导致您的代码在列表理解中不会中断,从而允许您在之后检查结果。