【发布时间】:2016-05-26 20:16:14
【问题描述】:
我的 Python 代码将 JSON POST 请求发送到服务,它会返回一个带有信息的 JSON。
我的代码:
for username in data:
for text in data[username]:
body = json.dumps({ "text": text['text'], "extract_type": "mitie"})
r = requests.post('http://localhost:3003/api/extract/run', data=body, headers=headers)
print "---New Request---"
print (r.content)
我得到的回应:
---New Request---
[{"score":0.6997741063788492,"tag":"LOCATION","label":"USA"},
{"score":1.0501661504998254,"tag":"MISC","label":"European"}]
---New Request---
[{"score":0.12021601772708868,"tag":"ORGANIZATION","label":"NFL"}]
---New Request---
[{"score":0.16843877285343356,"tag":"MISC","label":"Watermel"},
{"score":0.46122731000101685,"tag":"MISC","label":"Professional"},
{"score":0.6470543353899144,"tag":"LOCATION","label":"USA"}]
我正在尝试检查它是否具有"tag":"LOCATION",然后将label 提取到一个变量中。
我试过添加
for username in data:
for text in data[username]:
#print text['text']
body = json.dumps({ "text": text['text'], "extract_type": "mitie"})
r = requests.post('http://54.174.131.124:3003/api/extract/run', data=body, headers=headers)
print "---New Request---"
print (r.content)
if "LOCATION" in r.content['tag']:
location = r.content['label']
但我收到错误TypeError: string indices must be integers, not str
【问题讨论】:
-
既然你知道它是 JSON,你试过
r.json()吗? -
@jonrsharpe 我会在哪里添加它?我认为问题在于我的 if 语句,但我不知道该怎么做。
r.content是我的回复中显示的内容,因此该部分有效。 -
if r.json().get('tag') == 'LOCATION': ...?阅读字典。 -
r.content是一个或多个项目的列表。您需要从列表中获取每个项目,然后从中提取'tag'和'label'。
标签: python json http-post httprequest