2

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.

1
  • The + operator is for strings(generally). Your displayed in an object literal. Commented Aug 6, 2013 at 22:49

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.