Chud37
Chud37

Reputation: 5017

building a JSON string

I have a two part question (Very new to JSON)

  1. I need to build a json object out of attr 'data-id'. Can a JSON object be a single 'array' of numbers?
  2. I have got the code for this but I am struggling to build the JSON object, as follows:

code:

var displayed = {};
$('table#livefeed tr').each(function (i) {
    var peopleID = $(this).attr("data-id");
    //console.log("id: " + peopleID);
    if(peopleID!="undefined") displayed += peopleID;
});
console.log(displayed);

However this does not work properly, I just end up with string of objects added together.

Upvotes: 2

Views: 96

Answers (2)

scrappedcola
scrappedcola

Reputation: 10572

First you build and object then you use JSON.stringify(object); to create the string. But you also have an error. If you are checking peopleID to be defined you need to use typeof as an undefined attribute won't be the string 'undefined':

var displayed = [];
$('table#livefeed tr').each(function (i) {
    var peopleID = $(this).attr("data-id");
    //console.log("id: " + peopleID);
    if(typeof(peopleID)!="undefined") displayed.push(peopleID);
});
console.log(displayed);
var jsonDisplay = JSON.stringify(displayed);
console.log("JSON: " + jsonDisplay);

Upvotes: 0

Matt Bryant
Matt Bryant

Reputation: 4961

A JSON object can be an array of numbers.

Try something like this:

var displayed = [];
$('table#livefeed tr').each(function (i) {
    var peopleID = $(this).attr("data-id");
    if(peopleID!="undefined") 
        displayed.push(peopleID);
});
console.log(displayed);

To turn it into JSON,

JSON.stringify(displayed);

Upvotes: 6

Related Questions