user2981688
user2981688

Reputation: 37

How to create JSON object in jquery by getting values through iteration

I am new to JSON and jquery. I have the following use-case for which I need some help.

I need to create an array of objects in the following format:

{ "endpoint" : [ 
    { "ip": "16.140.23.90", "mac": "a2:35:67:e7" },
    { "ip": "16.140.23.91", "mac": "36:b1:79:ab" }
  ]
}

This is a sample of what I need (representing two rows only, there can be more). Now the value of ip and mac I need to add by iterating over a table's selected rows. E.g. there is a table on the GUI in which each row is having two columns "IP" and "MAC". I need to get the data of the selected rows in the above format.

How do I form the JSON array in the above format when I need to add the values of the attributes while iterating? Anything I can do using JSON.stringify API? If yes, then how do I form the string which I can pass to JSON.stringify which results in the above format?

Any help will be highly appreciated.

Upvotes: 2

Views: 860

Answers (3)

H77
H77

Reputation: 5967

If this is your table (first cell is ip and 2nd cell is mac)

<table id='tbl'>
    <tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
    <tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>

Pure JS

var ips = { "endpoint" : [] };
var tbl = document.getElementById('tbl');
for (var i=0; i<tbl.rows.length; i++) {
    ips["endpoint"].push({
        "ip" : tbl.rows[i].cells[0].innerHTML,
        "mac" : tbl.rows[i].cells[1].innerHTML
    });
}

Fiddle

jQuery

var ips = { "endpoint" : [] };
$(document).ready(function() {
    $('#tbl tr').each(function(i) {
        ips["endpoint"].push({
            "ip" : $(this).find('td:eq(0)').text(),
            "mac" : $(this).find('td:eq(1)').text()
        });
    });
    var json = (JSON.stringify(ips));
    document.getElementById('json').innerHTML = json;
});

Fiddle

Upvotes: 3

user2466202
user2466202

Reputation: 1205

The first answer is good. But since this question is in regard to jquery, I provide a similar solution using jquery to manipulate the DOM. The table is still the same:

<table id='tbl'>
    <tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
    <tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>

The javascript code to creat the json object:

var ips = { "endpoint": [] };
var rows = $('#tbl tr');
for (var i = 0; i < rows.length; i++) {
    ips["endpoint"].push({
        "ip": rows.eq(i).find("td").eq(0).text(),
        "mac": rows.eq(i).find("td").eq(1).text()
    });
}

Fiddle

Upvotes: 1

Mike Bell
Mike Bell

Reputation: 1376

JSON is just a serialized representation of javascript objects, so just make the objects in javascript and then serialize using the JSON.stringify method. If you're not sure how to make a javascript object and add values to an array, then you should do a little googling, since that's pretty basic stuff.

Upvotes: 0

Related Questions