I have Json of the form
[{"id":39,"data":1},{"id":40,"data":2}]
It does not parse properly with jQuery.parseJSON()
I need to take this data and create a html table
. I was thinking of creating the HTML dynamically in the js.
A. How can I parse the json?
B. Is dynamic html the best route?
Update
I apologize. Evidently my question is not clear. Here is the jquery
$.get('Service.aspx',
{ p1: value, p2: value },
function (data) {
notesJson = data;
alert(notesJson);//Json comes back as I said here...
var noteSet = jQuery.parseJSON(notesJson);
alert(noteSet.notes);
});
notes does exist in the Json. The second alert fails "undefined".
Ok based on you comment on your question:
Use $.getJSON
instead of $.get
:
$.getJSON('someurl', {/*somedata*/}, function(json_data){
//no need for parsejson
//use the json_data object
var table_obj = $('table');
$.each(json_data, function(index, item){
var table_row = $('<tr>', {id: item.id});
var table_cell = $('<td>', {html: item.data});
table_row.append(table_cell);
table_obj.append(table_row);
})
})
What you have is an array, you need an object. Try
{ "notes" : [{"id":39,"data":1},{"id":40,"data":2}] }
as the json
or do this
alert(noteSet[0]);
alert(noteSet[1]);
Here's another good library to simply achieve that: https://github.com/afshinm/Json-to-HTML-Table
Just pass the JSON data to this library and get the HTML table:
//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
You say you're using .NET so you could use
return Json(yourObject, JsonRequestBehavior.AllowGet);
instead of JavaScriptSerializer. You won't have to parse it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With