遍历JSON对象以获取特定值

时间:2020-01-28 11:58:24

标签: python json loops flask

我用烧瓶编写了Web应用程序,以接收来自另一个应用程序的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)

1 个答案:

答案 0 :(得分:0)

我能够使用此代码从JSON中检索特定项目...

def rp_webhook():
    if request.method == 'POST':
        results= request.json
        x=json.dumps(results)
        y=json.loads(x)