![](/img/trans.png)
[英]Trouble accessing data from a JSON object that was originally a Python dictionary in Flask
[英]how to get data from json object to a dictionary in python
我使用以下JavaScript代码将数据从javascript发送到视图,py
使用Javascript:
$(document).ready(function(){
console.log("js2 working");
var jsonData={},a=0,key;
$("#submit-button").click(function(e){
e.preventDefault();
$('.field').each(function () {
a+=1;
key=String(a);
jsonData[key] = this.value;
});
console.log(JSON.stringify(jsonData));
$.get('details',{"data":JSON.stringify(jsonData)}).done(function(){
console.log("posted successfully");
});
});
});
我得到一个JSON字符串:
{"1":"text","2":"text2",3:"text3"}
使用request.get来将views.py设置为int我需要提取views.py中的每个值
这是我在views.py中的代码:
def details(request):
latest_question_list = Question.objects.order_by('id')
count=0
for question in latest_question_list:
count+=1
answer=request.GET['data']
jsonData=json.loads(answer)
answer=jsonData(str(count))
entry = Answer(question = question,answer=answer)
entry.save()
return HttpResponse("feedback:contactus")
我在views.py中获取json,如上面所示,问题是在尝试提取值时。 请帮助我找到解决方案
jsonData
将转换为字典,以便您可以执行以下操作:
>>> print len(jsonData)
3
>>> print text = jsonData['1']
'text'
>>> print jsonData['2']
'text2'
>>> print jsonData['3']
'text3'
至于你的问题:
answer = request.GET['data']
jsonData = json.loads(answer)
for count, question in enumerate(latest_question_list):
answer = jsonData[str(count + 1)]
entry = Answer(question=question, answer=answer)
entry.save()
return HttpResponse("feedback:contactus")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.