简体   繁体   中英

how to get data from json object to a dictionary in python

i send data from javascript to views,py using the following javascript code

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");
});
});
});

i get a json string:

{"1":"text","2":"text2",3:"text3"}

int the views.py using request.get i need to extract each value in views.py

here is my code in 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")

i am getting the json in views.py as shown above the problem is while trying to extract value. please help me find a solution

jsonData is converted to a dictionary so that you can do the following:

>>> print len(jsonData)
3
>>> print text = jsonData['1']
'text'
>>> print jsonData['2']
'text2'
>>> print jsonData['3']
'text3'

As for your question:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM