将 javascript 对象或数组转换为 json 以获取 ajax 数据

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

Convert javascript object or array to json for ajax data

javascriptarraysjsonstringify

提问by Christine Wilson

So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!

所以我正在创建一个包含元素信息的数组。我遍历所有元素并保存索引。由于某种原因,我无法将此数组转换为 json 对象!

This is my array loop:

这是我的数组循环:

var display = Array();
$('.thread_child').each(function(index, value){
   display[index]="none";
   if($(this).is(":visible")){
      display[index]="block";
   }
});

I try to turn it into a JSON object by:

我尝试通过以下方式将其转换为 JSON 对象:

data = JSON.stringify(display);

It doesn't seem to send the proper JSON format!

它似乎没有发送正确的 JSON 格式!

If I hand code it like this, it works and sends information:

如果我像这样手动编写代码,它就会工作并发送信息:

data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};

When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.

当我对 JSON.stringify 对象发出警报时,它看起来与手动编码的一样。但它不起作用。

I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?

我快疯了试图解决这个问题!我在这里缺少什么?发送此信息以获取手动编码格式的最佳方式是什么?

I am using this ajax method to send data:

我使用这个ajax方法发送数据:

$.ajax({
        dataType: "json",
        data:data,
        url: "myfile.php",
        cache: false,
        method: 'GET',
        success: function(rsp) {
            alert(JSON.stringify(rsp));
        var Content = rsp;
        var Template = render('tsk_lst');
        var HTML = Template({ Content : Content });
        $( "#task_lists" ).html( HTML );
        }
    });

Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.

使用 GET 方法,因为我正在显示信息(不更新或插入)。只将显示信息发送到我的 php 文件。



END SOLUTION

最终解决方案



var display = {};
$('.thread_child').each(function(index, value){
   display[index]="none";
   if($(this).is(":visible")){
      display[index]="block";
   }
});

$.ajax({
        dataType: "json",
        data: display,
        url: "myfile.php",
        cache: false,
        method: 'GET',
        success: function(rsp) {
            alert(JSON.stringify(rsp));
        var Content = rsp;
        var Template = render('tsk_lst');
        var HTML = Template({ Content : Content });
        $( "#task_lists" ).html( HTML );
        }
    });

回答by Shital Shah

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

我不完全确定,但我认为您可能对数组在 JSON 中的序列化方式感到惊讶。让我们隔离问题。考虑以下代码:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

这将打印:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

这就是 JSON 实际序列化数组的方式。但是,您想看到的是:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

要获得这种格式,您需要序列化对象,而不是数组。所以让我们像这样重写上面的代码:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

这将以您想要的格式打印。

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

你可以在这里玩这个:http: //jsbin.com/oDuhINAG/1/edit?js,console

回答by JVE999

You can use JSON.stringify(object)with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

您可以使用JSON.stringify(object)对象,我刚刚编写了一个函数,该函数将递归地将数组转换为对象,JSON.stringify(convArrToObj(array))如下所示(可以在此答案中找到更多详细信息):

// 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;
}

To make it more generic, you can override the JSON.stringifyfunction and you won't have to worry about it again, to do this, just paste this at the top of your page:

为了使其更通用,您可以覆盖该JSON.stringify功能,而不必再次担心,为此,只需将其粘贴到页面顶部即可:

// Modify JSON.stringify to allow recursive and single-level 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){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringifywill accept arraysor objects! (link to jsFiddle with example)

现在JSON.stringify将接受arraysobjects!(链接到 jsFiddle 示例



Edit:

编辑:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array)alwaysreturns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringifywith an object):

这是另一个更有效的版本,尽管它可能会或可能不会那么可靠(不确定 - 这取决于是否JSON.stringify(array)总是返回[],我没有看到为什么它不会的太多原因,所以这个函数应该是更好,因为当您JSON.stringifyobject) 一起使用时,它的工作量会减少一点:

(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);
    };
})();

jsFiddle with example here

jsFiddle与示例here

js Performance test here, via jsPerf

js 性能测试在这里,通过 jsPerf