1

I have a Javascript variable which is an array (I push strings into it) and I have to send that list back to the server through an AJAX jQuery.POST() method:

var user_list = new Array();
user_list.push("42");
var data = { user_list: JSON.stringify(user_list)};
$.post('/accounts/ajax/user_verification/', data)
    .done( my_cb );

In the server, I am running Django and try to decode the POST request with the following view:

@login_required
def user_verification(request):

    if not request.POST.has_key('user_list'):
        print (__name__ + ', user_verification, raising BadRequest.')
        raise Exception("'user_list' not found as a POST parameter.")

    value = unicode(request.POST['user_list'])
    print (__name__ + ', value, v = ' + value)
    user_list = json.loads(request.body) 

I get the following output and posterior exception thrown by " json.loads(request.body) ":

accounts.ajax, value, v = ["42"]
ValueError: No JSON object could be decoded

Isn't ["42"] a valid JSON array definition with a single element?

3
  • try passing {"42"} instead of ["42"] Commented Dec 1, 2013 at 9:39
  • But I am using JSON.stringify(), isn't its output correct? Commented Dec 1, 2013 at 9:40
  • try changing the 'key' user_list in your JSON structure to something else. It might causing the problem. Also, to be on the safe side, can you change the JSON to var data = { "newKey": JSON.stringify(user_list)}? Commented Dec 1, 2013 at 13:46

2 Answers 2

1

I don't know anything about Django, so, this a total guess :D

import json
...
value = json.load(request.POST['user_list'])
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I think that it is too late... I made a mistake while passing the arguments to json.load().
@Ricardo I just realized that there is another function called loads, and that you were already using it, so, I was a bit off-topic apparently (one more time) :D Glad if it helped in some way.
1

I might be completely wrong here, but it seems to me that you are trying to decode a wrong thing. If I'm not mistaken, you request.body looks like this:

user_list=["42"]

and if you try to decode this, you have a problem. So why don't you decode the value from variable value?

user_list = json.loads(value) 

Comments

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.