无法在POST请求中获取json属性

时间:2016-10-06 08:31:02

标签: python json post bottle

此Json作为POST请求收到。现在 我希望获得text数组

中每个条目的actions键的值

我正在使用Python的瓶子来接收请求。 为了获取必需属性的值,我做了这个

word = request.forms.get('[attachments][actions][0][text]')

但这并不能打印所需的价值。

{
  "attachments": [
    {
      "title": "XYZ",
      "title_link": "EDWE",
      "text": "dxjhvgebndm",
      "fields": [
        {
          "title": "Food",
          "value": "$20",
          "short": true
        }
      ],
      "actions": [
        {
          "name": "chess",
          "text": "Approve",
          "type": "button",
          "value": "chess",
          "style": "primary"
        },
        {
          "name": "maze",
          "text": "Decline",
          "style": "danger",
          "type": "button",
          "value": "maze"
        },
        {
          "name": "war",
          "text": "More details",
          "style": "default",
          "type": "button",
          "value": "war",
          "confirm": {
            "title": "Are you sure?",
            "text": "Would you like to see more details of your expense?",
            "ok_text": "Yes",
            "dismiss_text": "No"
          }
        }
      ],
      "image_url": "",
      "thumb_url": "https://i.imgsafe.org/cf40eef.png",
      "footer": "fghj",
      "footer_icon": "https://i.imgsafe.org/cf2e0eef.png",
      "ts": 1475057533
    }
  ]
}

注意:我收到完整的JSON,问题在于获取正确的属性。

修改 通过这个我收到POST请求

import json
from bottle import route, run, request
import urllib

@route('/ocr_response', method='POST')
def ocr_response():
    body = request.body.read()
    word = request.forms.get('[attachments][actions][0][text]')
    print word
    print body


if __name__ == "__main__":
    run(host='0.0.0.0', port=80, debug=True)

1 个答案:

答案 0 :(得分:3)

根本不是你如何访问字典中的项目。

首先,JSON数据可通过request.json获得。其次,我不确定你用你正在传递的字符串做什么,但是你需要使用普通的字典/数组语法。第三,附件就像动作一样是一个列表,所以你也需要在那里添加一个索引。

request.json['attachments'][0]['actions'][0]['text']