Python过滤器特定的后响应

时间:2016-05-26 20:16:14

标签: python json http-post httprequest

我的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

1 个答案:

答案 0 :(得分:0)

在请求中,repsonse content是原始响应,它是一个字符串。您正在尝试将其用作dict,这就是r.content['tag']引发TypeError的原因。

为了使用响应json数据,您需要使用r.json()解码json响应。它将返回一个dicts列表(问题中的json数据,已解码),您可以通过'tag'过滤,然后提取标签。