[javascript] Convert javascript object or array to json for ajax data

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!

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:

data = JSON.stringify(display);

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

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.

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({
        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.


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

This question is related to javascript arrays json stringify

The answer is


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):

// 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.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// 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.stringify will accept arrays or objects! (link to jsFiddle with example)


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) always returns [], 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.stringify with an object):

(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

js Performance test here, via jsPerf


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to stringify

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Convert javascript object or array to json for ajax data JSON.stringify output to div in pretty print way how to use JSON.stringify and json_decode() properly Serializing object that contains cyclic object value