简体   繁体   中英

Django/JS: json.dumps and parse.json

I'm no programmer, so I can't go to source code of Django or Jquery and figure out how and why these function don't return what I want from them, because I simply wouldn't understand the source code.

I do one little project for myself and here's my confusion about json part: here's my django/python function:

def searchPatients(request):
    patients = Patients.objects.filter(KeyName__icontains=request.POST.get('KeyName'))
    response = []
    for patient in patients:
        tmpvar = {}
        tmpvar = { 'Name1':patient.Name1, 'Name2':patient.Name2 }
        response.append(tmpvar)
    return HttpResponse(json.dumps(response), content_type="application/json")

I checked in shell, json.dumps(response) gave me this:

'[{"Name2": "TestName2", "Name1": "TestName1"}, {"Name2": "TempName2", "Name1": "TempName1"}]'

Looks ok form me. And then I don't understand part starts. This is my JS/JQuery function:

input_newRecord_Search.keyup(function() {
    $.post('/edit/ajax_search_patients', { KeyName: $(this).val() }, function(data) {
        var patients = jQuery.parseJSON(data);
        for (var patient in patients) {
        $('#searchResults ul').append('<li>'+patients[patient].Name1+'</li><li>+'patients[patient].Name2+'</li>');
        };
    }, "json");
});

I get an error: "SyntaxError: JSON.parse: unexpected character". I checked what data jquery gets from server: console.log(data):

[{Name2: "TestName2", Name1: "TestName1"}, {Name2: "TempName2", Name1: "TempName1"}]

So, as far as I know JSON syntax looks like - {"key":"value"} and I'm missing quotes on key field. And I don't understand why I'm missing them. I can put them manually through regex, for instance, but I don't think it's the right way. And using regex I can parse my entire data without need of jQuery.parseJSON(), but again I want to use jQuery function - after all it was made exactly for this purpose. Can anyone help me with this one?

The trick is that when you tell jQuery.post that the server is returning JSON it parses it for you .

// This line can be safely removed;
// jQuery is doing it for you behind the scenes
var patients = jQuery.parseJSON(data);

When you use parseJSON on the already parsed data you wind up trying to parse the string representation of a JavaScript object. Simply use the already parsed data and everything should work correctly.

jQuery is automatically converting the json to js objects for you. You don't need to call parse yourself.

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