[英]receive and loop through json data in python
我有一個JSON
數據,我使用AJAX
發送到我的服務器。 數據來到這里,我看到了。
def add_collection(self):
form = AccountForm.LoginForm(request.form)
if self.request.method == 'GET' :
return render_template('add_collection.html',user=current_user,formLogin = form)
elif self.request.method == 'POST' :
for data in self.request.data :
print "The data is %s" %data
當我打印self.request.data時,我得到了我的JSON
[{"image":"https://mybucket.s3.amazonaws.com/asma.jpg","Description":"Photo Descriptiong"},
{"image":"https://mybucket.s3.amazonaws.com/NCg3G.png","Description":"Photo Description"}]'
以上就是我的JSON
文件的樣子和我期待的內容。 但是,我想將它分成兩行並插入數據庫。 請問我如何循環JSON
。 我在這里看到過類似的問題以及更多問題。 但是,沒有一個適合我。 我試過的時候
for data in self.request.data :
print data['image']
TypeError:字符串索引必須是整數,而不是str
請問我如何實現這一目標?任何幫助將不勝感激。
以下是我的ajax請求。
$.ajax({
url: "/user/add_collection",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(arr),
dataType:'json',
success : function(data,status){
console.log("The image upload data returns", data);
console.log("the image upload status is", status);
},
error : function(xhr, ajaxOptions, thrownError){
//$.mobile.loading('hide');
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
我正在使用python運行flask框架。
我認為你將響應作為一個字符串(self.request.data)。 要將其視為對象,首先需要將其轉換為(從字符串到python表示):
elif self.request.method == 'POST' :
parsed_json = json.loads(self.request.data)
for data in parsed_json:
print data['image']
JSON數據作為字符串接收。 你需要先解析它。
data = json.loads(self.request.data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.