If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = \'val1\';
row.Col2 = \'val2\';
lst.push(row);
And then convert it
Because row
is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str
function (called by JSON.stringify
):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for
loop, which only enumerates the array elements. Objects are iterated with a for...in
loop, with a hasOwnProperty
test to make sure the proeprty actually belongs to this object.