Jason
Jason

Reputation: 11363

JSON.parse error on simplejson return in Django

I have a view page that currently has two columns of data shown, soon to be expanded to four. Each column contains the result of a QuerySet for that particular model.

Here's what I have in my views.py method:

if request.REQUEST["type"] == "text":
        client = Client.objects.get(client_name = request.REQUEST["search"])
        peerList = ClientPeers.objects.prefetch_related().filter(client = client.client)
        compList = ClientCompetitors.objects.prefetch_related().filter(client = client.client)

else:
    peerList = ClientPeers.objects.prefetch_related().filter(client = request.REQUEST["search"])
    compList = ClientCompetitors.objects.prefetch_related().filter(client = request.REQUEST["search"])

for peer in peerList:
    peerlst.append({"pid" : peer.parentorg.parentorg, "pname" : peer.parentorg.parentorgname})

for comp in compList:
    complst.append({"cid" : comp.parentorg.parentorg, "cname" : comp.parentorg.parentorgname})

lst.append(simplejson.dumps(peerlst))
lst.append(simplejson.dumps(complst))

return HttpResponse(simplejson.dumps(lst), mimetype = "text/json")

This allows me to send a 2D array of data to the browser in the format

[ { //JSON }, { //JSON } ]

In my jQuery.ajax success function, I have

function handler(results) {
  var data = JSON.parse(results);

  for (var i = 0; i < data[0].length; i++)
    $("#available_peers").append("<li>" + data[0][i].pname + "</li>");

  for (var i = 0; i < data[1].length; i++)
    $("#available_competitors").append("<li>" + data[1][i].cname + "</li>");

Firebug shows that the GET request works and I can see the data in the response tab. However, the console prints out

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
var data = JSON.parse(results)

This error disappears if I replace var data = JSON.parse(results) with

var peers = JSON.parse(data[0]);
var comps = JSON.parse(data[1]);

Why does one method work but another doesn't?

Upvotes: 2

Views: 805

Answers (1)

Austin Phillips
Austin Phillips

Reputation: 15746

The jQuery ajax() call will make an intelligent guess as to the returned data type. In your example, function handler(results), the results variable will already be a decoded JSON object, containing two items in an array. The reason that JSON.parse(data[0]) works, is that you have returned JSON encoded data as a string.

Don't encode the individual list elements to JSON before placing in the output array:

lst.append(peerlst)  # <-- Don't encode to JSON string here
lst.append(complst)

return HttpResponse(simplejson.dumps(lst), mimetype = "application/json") # <-- Single JSON encoding

Upvotes: 1

Related Questions