JavaScript 关联数组到 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4425289/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:21:35  来源:igfitidea点击:

JavaScript associative array to JSON

javascriptjsonassociative-array

提问by ActionOwl

How can I convert a JavaScript associative array into JSON?

如何将 JavaScript 关联数组转换为 JSON?

I have tried the following:

我尝试了以下方法:

var AssocArray = new Array();

AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]);

// result: "a = The letter A"

JSON.stringify(AssocArray);

// result: "[]"

回答by Felix Kling

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

数组应该只有带有数字键的条目(数组也是对象,但你真的不应该混合这些)。

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the lengthof the array:

如果您将数组转换为 JSON,则该过程将仅考虑数字属性。其他属性被简单地忽略,这就是为什么你得到一个空数组的原因。如果您查看length数组的,这可能更明显:

> AssocArray.length
0

What is often referred to as "associative array" is actually just an object in JS:

通常所说的“关联数组”实际上只是 JS 中的一个对象:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.ais the same as AssocArray['a'].

可以通过数组表示法或点表示法(如果键不是保留关键字)访问对象的属性。因此AssocArray.a与 相同AssocArray['a']

回答by AndreKR

There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.

JavaScript 中没有关联数组。但是,有些对象具有命名属性,所以不要用 初始化“数组” new Array,然后它就变成了通用对象。

回答by killer_kohlrabi

Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:

同意将对象保留为对象并将数组保留为数组可能是最佳实践。但是,如果您有一个带有命名属性的对象并将其视为数组,则可以这样做:

let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
    tempArr.push(objectArr[element]);
});

let json = JSON.stringify(tempArr);

回答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 Yene Mulatu

You might want to push the object into the array

您可能希望将对象推送到数组中

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);