JSON.stringify serializes to [[]]

后端 未结 4 2035
粉色の甜心
粉色の甜心 2021-01-25 18:39

If I create a JavaScript object like:

var lst = [];
var row = [];
row.Col1 = \'val1\';
row.Col2 = \'val2\'; 
lst.push(row);

And then convert it

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 19:09

    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.

提交回复
热议问题