问题描述
如果我创建一个JavaScript对象,如:
If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
然后将其转换为字符串:
And then convert it to a string:
JSON.stringify(lst);
结果是一个包含空对象的对象:
The result is an object containing an empty object:
[[]]
我希望它序列化如:
[[Col1 : 'val1', Col2: 'val2']]
为什么内部对象属性不能序列化?
Why do the inner objects properties not serialize?
推荐答案
因为 row
是一个数组,而不是一个对象。将其更改为:
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"}]
更新
要了解到底发生了什么,你可以看看。这是来自 str
函数的(大大减少)片段(由 JSON.stringify
调用):
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)) {
//...
}
//...
}
//...
请注意,对于循环使用正常的迭代数组,它只枚举数组元素。使用
for
循环迭代对象,使用 hasOwnProperty
测试以确保proeprty实际属于这个对象。
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.
这篇关于JSON.stringify序列化为[[]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!