5

I'm trying to parse json data in django view. But I got a problem.

I'm using below code snippet.

$(document).ready(function(){
    $("#mySelect").change(function(){
        selected = $("#mySelect option:selected").text()
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            url: '/test/jsontest/',
            data: {
                   'fruit': selected,
                  },
            success: function(result) {
                    document.write(result)
                    }
    });
  });
});

when the client side user change the value, ajax code send json data. But server side view receive a data in forms with "fruit=apple". I think it's not json data format. So, I have no idea how to parse the data.

I try to parse like below, But I got 500 Internal server error after calling json.dumps(data)

class JsonRead(View):
    template_name = 'MW_Etc/jsonpost.html'
    def get(self,request):
        return render(request, self.template_name)

    def post(self,request):
        data = request.body
        logger.debug('json data received(%s)' % data)
        return HttpResponse(json.dumps(data), content_type='application/json')

2 Answers 2

8

Do post JSON string like this.

data: {'data': JSON.stringify({'fruit': selected})}

and receive like

data = json.loads(request.POST.get('data', ''))

Sign up to request clarification or add additional context in comments.

1 Comment

If he removed the single quotes like:data: {fruit: selected}, he would successfully do fruit = json.loads(request.POST.get('fruit'))
6

You need to post the data as JSON string rather than a JavaScript object.

data: JSON.stringify({'fruit': selected})

should do. Also note that you'll then need to json.loads the data in Django to actually do anything with it.

5 Comments

as you mention, I add jsondata=json.loads(request.body). but I got 500 error.
Did you edit the JavaScript client side as well? Try logging the error to see what is wrong (try: ... except Exception, e: logger.exception(e)).
exception caused by "the JSON object must be str, not 'bytes'", how can I resolve this?
I've never encountered that myself, but maybe this will help: stackoverflow.com/questions/25968752/…
json.loads( request.body.decode('utf-8') ) works for me!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.