JSON.stringify 不适用于普通的 Javascript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16196338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.stringify doesn't work with normal Javascript array
提问by Sherlock
I must be missing something here, but the following code (Fiddle) returns an empty string:
我一定在这里遗漏了一些东西,但以下代码(Fiddle)返回一个空字符串:
var test = new Array();
test['a'] = 'test';
test['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
What is the correct way of JSON'ing this array?
JSON'ing 这个数组的正确方法是什么?
回答by Quentin
JavaScript arrays are designed to hold data with numericindexes. You can add named properties to them because an array is a type of object(and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
JavaScript 数组旨在保存带有数字索引的数据。您可以向它们添加命名属性,因为数组是一种对象类型(当您想要存储有关包含普通、有序、数字索引数据的数组的元数据时,这会很有用),但这不是它们的设计初衷为了。
The JSON array data type cannothave named keys on an array.
JSON 数组数据类型不能在数组上具有命名键。
When you pass a JavaScript array to JSON.stringifythe named properties will be ignored.
当您将 JavaScript 数组传递给JSON.stringify命名属性时,将被忽略。
If you want named properties, use an Object, not an 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);
回答by Adrien Louis Combecau
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
上面的解释和例子很好。我发现这个(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;
}
it works fine and the output of the test:
它工作正常,测试输出:
console.log(json);
Result:
结果:
"{"a":"test","b":["item","item2","item3"]}"
回答by JVE999
I posted a fix for this here
我在这里发布了一个修复程序
You can use this function to modify JSON.stringifyto encode arrays, just post it near the beginning of your script (check the link above for more detail):
您可以使用此函数修改JSON.stringify为 encode 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);
};
})();
回答by JVE999
Alternatively you can use like this
或者你可以像这样使用
var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);
Like this you JSON-ing a array.
像这样你 JSON-ing 一个数组。
回答by user2217603
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
Json 必须有键值对。你仍然可以有一个数组作为值部分。因此,添加您选择的“关键”:
var json = JSON.stringify({whatver: test});
var json = JSON.stringify({whatver: test});

