gpt4 book ai didi

python - 从python中的请求查询结果中提取一个json字段

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:46 26 4
gpt4 key购买 nike

如何从以下代码的结果中提取特定字段??

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

我无法提取文本或用户等字段。

最佳答案

Response.json返回一个经过 json 解码的对象。只需使用 k 作为 python 对象:

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

关于python - 从python中的请求查询结果中提取一个json字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36472371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com