Python 循环浏览发布到Flask应用程序的JSON内容
我正在尝试将JSON数据发布到flask应用程序。然后应用程序应该循环遍历数组中的每个对象并返回结果。如果数组中只有一个对象,我就能够返回对象中每个值的结果。但任何包含多个对象的JSON数据都会产生500个内部服务器错误 我错过了什么Python 循环浏览发布到Flask应用程序的JSON内容,python,json,flask,flask-restful,Python,Json,Flask,Flask Restful,我正在尝试将JSON数据发布到flask应用程序。然后应用程序应该循环遍历数组中的每个对象并返回结果。如果数组中只有一个对象,我就能够返回对象中每个值的结果。但任何包含多个对象的JSON数据都会产生500个内部服务器错误 我错过了什么 from flask import Flask, url_for app = Flask(__name__) from flask import request fro
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:
print(i['Location'])
print(i['Item_id')
print(i['Price'])
print(i['Text'])
顺便说一句:下次在调试模式下运行
app.run(debug=True)
您可以在网页上看到更多信息。您有列表,所以需要
for i in foo:
print(i['Location'])
print(i['Item_id')
print(i['Price'])
print(i['Text'])
顺便说一句:下次在调试模式下运行
app.run(debug=True)
您可以在网页上看到更多信息。实际上,使用以下代码:
for i in foo['Location']:
Item_id = i['Item_id']
Price = i['Price']
output = output + Item_id + Price
# do stuff here later
您的意思是,您得到的第一个元素是位置对象。
事实上,当您有多个对象时,您得到的第一个元素是location元素的列表。因此,在使用位置对象之前,必须在此列表上执行循环
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
实际上,使用此代码:
for i in foo['Location']:
Item_id = i['Item_id']
Price = i['Price']
output = output + Item_id + Price
# do stuff here later
您的意思是,您得到的第一个元素是位置对象。
事实上,当您有多个对象时,您得到的第一个元素是location元素的列表。因此,在使用位置对象之前,必须在此列表上执行循环
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
对于foo中的i:i['Location']
。顺便说一句:在调试模式下运行,您应该可以在网页上看到更多信息。对于foo:i['Location']
。顺便说一句:在调试模式下运行,您应该可以在网页上看到更多信息。