【发布时间】:2020-01-28 11:58:24
【问题描述】:
我在烧瓶中编写了网络应用程序以接收来自另一个应用程序的 JSON 格式的 POST 请求...
import os
from flask import Flask,request,json,abort
app=Flask(__name__)
@app.route('/webhook',methods=['POST'])
def webhook():
if request.method == 'POST':
print(request.json)
return '',200
else:
abort(400)
if __name__=='__main__':
app.run()
我得到的数据:
{'channel': {'address': '00000', 'name': "nobody's Talking": 0000", 'uuid': 'fec375b2-d025-4a89-8688-2b1785dfb5d4'}, 'contact': {'name': 'Nets', 'urn': 'tel:+256704909243', 'uuid': 'af7065f4-192f-4a3a-9e08-75828394fb99'}, 'flow': {'name': 'webhook-test', 'revision': 4, 'uuid': '5041343f-4364-4518-a000-f4a4a7ff657f'}, 'input': {'attachments': [], 'channel': {'address': '00000', 'name': "nobody's Talking: 00000", 'uuid': 'fec375b2-d025-4a89-8688-2b1785dfb5d4'}, 'created_on': '2020-01-28T10:48:57.778339+03:00', 'text': 'whtest', 'type': 'msg', 'urn': {'display': '0704 909243', 'path': '+254704888680', 'scheme': 'tel'}, 'uuid': '554e6bfb-695e-4692-94ff-7ea9bfd936d0'}, 'path': [{'arrived_on': '2020-01-28T10:48:57.778606+03:00', 'exit_uuid': '', 'node_uuid': '23c305fb-da32-4217-9cf0-9bbf5d70ae56', 'uuid': '3a18d969-4880-484a-826a-60f18483623e'}], 'results': {}, 'run': {'created_on': '2020-01-28T10:48:57.778600+03:00', 'uuid': '32ec37f1-1ef6-4460-af89-305903114096'}}
我想遍历这个 json 对象并从对象中只检索三个项目。我以前没有使用过 json。这是我的尝试
def rp_webhook():
if request.method == 'POST':
results=(request.json)
for i in jsonobj['results']:
print(i['date created'],['flow'],['display'])
return '',200
else:
abort(400)
【问题讨论】:
-
你期待什么输出?这很令人困惑,例如,
urn在您的 JSON 中定义了两次,既作为字符串元素,又作为对象。 -
提示:没有“json 对象”这样的东西。 JSON 是一种文本格式,一旦反序列化,你所拥有的是一个普通的 Python 对象 - 通常(如你的情况)一个
dict包含嵌套的dicts 和lists。 -
@Rúben 很抱歉我已经编辑了它...“创建日期”,流程:名称和显示
-
您在上面显示的“我得到的数据”既不是 JSON,也不是声明
dict的 Python 代码。提示:使用repr()打印用于调试的内容,而不是print()。