sharad-garg
sharad-garg

Reputation: 469

How to parse JSON Array in java script

I am returning SQL Query result as a JSONArray to a JSP page. Now i want to show the data. I have written a code but it is working fine only for 23 objects in the JSONArray if JSONArray contains more the 23 object eval or JSON.parse function doesn't work. Please let me know how to solve this problem.

Below is the JS code i have written to iterate over this JSONArray.

var data = '<%=(JSONArray) request.getAttribute("resultArray")%>';
data = eval("(" + data + ")");
$(document).ready(function() {
   var table = $('<table/>').appendTo($('#column'));

   var rows = $('<tr/>').appendTo(table);
    $.each(data, function(rowid, row) {
       var rows = $('<tr/>').appendTo(table);
       $.each(row, function(column, data) {
           ($('<td/>').text(data)).appendTo(rows);
       })}); 
});

Upvotes: 2

Views: 1292

Answers (1)

BalusC
BalusC

Reputation: 1108742

Just don't let JSP print it as a JS string syntax within quotes (which obviously needs to be parsed in order to get a JS object). Get rid of those quotes. JSON is already in proper JS object syntax. That's also all what "JSON" stands for.

var data = <%=request.getAttribute("resultArray")%>;
$(document).ready(function() {
    // ...
});

By the way, using scriptlets in JSP is a poor practice. If you're on JSP 2.0 already (which is out for almost a decade already), just use EL.

var data = ${resultArray};
$(document).ready(function() {
    // ...
});

Note, also here, just don't quote it. It becomes otherwise a JS string instead of a JS object.


Unrelated to the concrete problem, is it absolutely necessary to introduce the extra JSON/jQuery step here? Why don't you just use for example JSTL to let JSP generate the desired HTML in the server side instead of JS/jQuery in the client side?

Upvotes: 3

Related Questions