Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - JSON to <table>

Tags:

jquery

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".

like image 719
P.Brian.Mackey Avatar asked May 13 '11 19:05

P.Brian.Mackey


4 Answers

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);
    })

})
like image 139
Naftali Avatar answered Sep 30 '22 18:09

Naftali


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]);
like image 35
Hogan Avatar answered Sep 30 '22 20:09

Hogan


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');
like image 22
Afshin Mehrabani Avatar answered Sep 30 '22 19:09

Afshin Mehrabani


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.

like image 41
Julien Avatar answered Sep 30 '22 20:09

Julien