I have a two part question (Very new to JSON)
- I need to build a json object out of attr 'data-id'. Can a JSON object be a single 'array' of numbers?
- 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.
carlosfigueira
87.7k14 gold badges137 silver badges176 bronze badges
asked Aug 6, 2013 at 22:45
Chud37
5,03714 gold badges69 silver badges130 bronze badges
2 Answers 2
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);
answered Aug 6, 2013 at 22:49
Matt Bryant
4,9714 gold badges33 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Aug 6, 2013 at 22:52
scrappedcola
10.6k1 gold badge36 silver badges48 bronze badges
Comments
lang-js
+operator is for strings(generally). Yourdisplayedin an object literal.