2016-04-07 60 views
2

如何從下面的代碼結果中提取特定的字段?從python中的請求查詢結果中提取json字段

payload = {'token': 'XXXXXXXX', 'channel': 'C0L8MGLMN' , 'count': '10'} 
r = requests.get('https://slack.com/api/channels.history', params=payload) 
print r.status_code 
pprint(r.json()) 

print "---------------------------" 
k = r.json() 
print "Now printing some cool stuff" 
response_dict = json.loads(k) 
response_dict['text'] 

這導致:

200 
{u'has_more': False, 
u'is_limited': True, 
u'messages': [{u'text': u'This is not a test!', 
       u'ts': u'1459763505.000003', 
       u'type': u'message', 
       u'user': u'U03FE3Z7D'}, 
       {u'subtype': u'bot_message', 
       u'text': u'This is a test!', 
       u'ts': u'1459750060.000002', 
       u'type': u'message', 
       u'username': u'facsimile_test'}], 
u'ok': True} 
--------------------------- 
Now printing some cool stuff 
Traceback (most recent call last): 
    File "clean_SLACK.py", line 17, in <module> 
    response_dict = json.loads(k) 
    File "/usr/lib/python2.7/json/__init__.py", line 338, in loads 
    return _default_decoder.decode(s) 
    File "/usr/lib/python2.7/json/decoder.py", line 366, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
TypeError: expected string or buffer 

我不能夠提取,如文本或用戶等

回答

3

Response.json領域返回一個對象,它是JSON解碼。只需使用k作爲python對象:

k = r.json() 
print "Now printing some cool stuff" 
for msg in k['messages']: 
    print msg['text'] 
相關問題