How to return a JSON object in classic ASP

Flash picture Flash · Aug 8, 2011 · Viewed 65.7k times · Source

I want to return a JSON object using a classic ASP script (it's part of an AJAX request).

If I just send the reponse as text like:

response.write("{ query:'Li', suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], data:['LR','LY','LI','LT'] }")

will this work, or do I actually need a JSON library?

Edit: I'm trying to get the autocomplete plugin at http://www.devbridge.com/projects/autocomplete/jquery/#howto to work.

javascript:

 $(document).ready(function() {
    var a = $('#txtValue').autocomplete({ 
    serviceUrl:'script.asp',
    minChars:2, 
    maxHeight:400,
    width:300,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});

ASP:

<% 
response.ContentType = "application/json"
response.write("{ query:'Li', suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], data:['LR','LY','LI','LT'] }") 
%>

Autocomplete is not working. It works if I use a local lookup array like lookup: ['January', 'February', 'March', 'April', 'May']

But there's something wrong with the ajax meaning it doesn't return the list properly.

Answer

Joe Enos picture Joe Enos · Aug 8, 2011

It appears to be a parsing error on the client side.

I didn't think this would make a difference, but it looks like if you quote everything, including the property names, it seems to work. And use double-quotes instead of single quotes - that apparently is making a difference.

Remember to double your double-quotes (at least I think that's how you do it in VBScript - been a long time).

So:

<%
    Response.ContentType = "application/json"
    Response.Write("{ ""query"":""Li"", ""suggestions"":[""Liberia"",""Libyan Arab Jamahiriya"",""Liechtenstein"",""Lithuania""], ""data"":[""LR"",""LY"",""LI"",""LT""] }")
%>