我必须在这里遗漏一些东西,但是下面的代码(Fiddle)返回一个空字符串:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
Run Code Online (Sandbox Code Playgroud)
JSON这个阵列的正确方法是什么?
Que*_*tin 110
普通的JavaScript数组用于保存带有数字索引的数据.您可以将命名键填充到它们上(当您想要存储关于包含正常,有序,数字索引数据的数组的元数据时,这可能很有用),但这不是它们的设计目的.JSON数组数据类型不能在数组上具有命名键.
如果需要命名键,请使用Object,而不是Array.
const test = {}; // Object
test.a = 'test';
test.b = []; // Array
test.b.push('item');
test.b.push('item2');
test.b.push('item3');
test.b.item4 = "A value"; // Ignored by JSON.stringify
const json = JSON.stringify(test);
console.log(json);Run Code Online (Sandbox Code Playgroud)
小智 9
上面的好解释和例子.我发现这个(JSON.stringify()数组与Prototype.js的奇异性)来完成答案.有些网站使用JSONFilters实现自己的toJSON,所以删除它.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
Run Code Online (Sandbox Code Playgroud)
它工作正常和测试的输出:
console.log(json);
Run Code Online (Sandbox Code Playgroud)
结果:
"{"a":"test","b":["item","item2","item3"]}"
Run Code Online (Sandbox Code Playgroud)
我在这里发布了一个修复程序
您可以使用此函数进行修改JSON.stringify以进行编码arrays,只需将其发布在脚本的开头附近(请查看上面的链接以获取更多详细信息):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122021 次 |
| 最近记录: |