【问题标题】:Loop through JSON content posted to Flask app循环发布到 Flask 应用程序的 JSON 内容
【发布时间】:2017-01-27 10:26:10
【问题描述】:

我正在尝试将 JSON 数据发布到烧瓶应用程序。然后应用程序应该循环遍历数组中的每个对象并返回结果。如果数组中只有一个对象,我可以返回对象中每个值的结果。但是任何具有多个对象的 JSON 数据都会产生 500 Internal Server 错误。

我在这里缺少什么?

            from flask import Flask, url_for
            app = Flask(__name__)
            from flask import request
            from flask import json

            @app.route('/messages', methods = ['POST'])
            def api_message():

                if request.headers['Content-Type'] == 'application/json':
                    foo = request.get_json()
                    output = ""
                    for i in foo['Location']:
                      Item_id = i['Item_id']
                      Price = i['Price']
                      output = output + Item_id + Price
                      # do stuff here later
                    return output
                else:
                    return "415 Unsupported"


            if __name__ == '__main__':
                app.run()

我在一个终端中运行上述代码,当我将 JSON 数据发布到另一个终端时,我得到“500 Internal Server error”:

            curl -H "Content-type: application/json" \ -X POST http://127.0.0.1:5000/messages -d '[{"Location":"1","Item_id":"12345","Price":"$1.99","Text":"ABCDEFG"},{"Location":"2","Item_id":"56489","Price":"$100.99","Text":"HIJKLMNO"},{"Location":"3","Item_id":"101112","Price":"$100,000.99","Text":"PQRST"}]'

【问题讨论】:

  • for i in foo: i['Location'] 。顺便说一句:在调试模式下运行,您应该会在网页上看到更多信息。

标签: python json flask flask-restful


【解决方案1】:

你有清单,所以你需要

for i in foo:
    print(i['Location'])
    print(i['Item_id')
    print(i['Price'])
    print(i['Text'])

顺便说一句:下次在调试模式下运行

app.run(debug=True)

您会在网页上看到更多信息。

【讨论】:

    【解决方案2】:

    其实,用这段代码:

    for i in foo['Location']:
        Item_id = i['Item_id']
        Price = i['Price']
        output = output + Item_id + Price
        # do stuff here later
    

    你说你得到的第一个元素是一个位置对象。 事实上,当你有多个对象时,你得到的第一个元素是位置元素的list。所以你必须在使用你的位置对象之前在这个列表上执行一个循环。

    for location_object in foo :
        for i in location_object["Location"] :
            Item_id = i['Item_id']
            Price = i['Price']
            output = output + Item_id + Price
            # do stuff here later
    

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多