2014-01-10 105 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()將導致您的代碼在列表理解中不會中斷,從而允許您在之後檢查結果。