Parse an unknown JSON with Jquery

Sometime it happens to receive a JSON string than need to be visualized without knowing the structure. Suppose we have an HTML table:

<tbody id="reportTable">					
</tbody>

To populate this table with jQuery it’s possible to use this simple code:

var rows = ${reportRows};
var html = $.each(rows, function(key, value){
 
	$("#reportTable").append("<tr>");
 
	$.each(value, function (key, data) {
		$("#reportTable").append("<td>" + data + "</td>");
	});
 
	$("#reportTable").append("</tr>");
 
});

${reportRows} comes from a Spring MVC Controller and it’s a Java string generates using Jackson (or Gson) in this way:

ColumnMapRowMapper rowMapper = new ColumnMapRowMapper();
List<Map<String, Object>> reportDataList =  getJdbcTemplate().query(sqlComplete, rowMapper);
 
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(reportDataList);

So, we have a query that return a not know number of column (suppose your code dynamically generate the query), we translate the results in JSON and we use jQuery to render the results.

Tagged , , ,