【问题标题】:Python Filter Specific Post ResponsePython 过滤器特定的后响应
【发布时间】: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


【解决方案1】:

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

为了使用响应json数据,你需要使用r.json()解码json响应。它将返回一个字典列表(问题中的 json 数据,已解码),您可以通过“标签”对其进行过滤,然后提取标签。

【讨论】:

  • 我用 decoded = r.json() if decoded.get("tag") == 'LOCATION': print "test" 替换了我的代码中的 if 语句,我收到了 AttributeError: 'list' object has no attribute 'get'. 我现在明白了 r.content 和 r.json() 之间的区别,但是我不确定为什么这不起作用。
  • @Joey 啊,对不起;你的 JSON 是一个 list 的字典。
  • 这是因为你的数据是一个json对象的列表,在python中被解码为一个dicts列表。所以在你的代码中,decoded 是一个列表(字典),但不是字典,这就是decoded.get("tag") 失败的原因。但是decoded[0].get("tag")decoded[1].get("tag") 等会按预期工作。
猜你喜欢
  • 2011-11-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多