Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 );
        }
    });
share|improve this question
2  
Do you mean to use JSON.parse? –  fbynite Nov 14 '13 at 5:38
    
Console.log the your data var. data = JSON.stringify(display); console.log(data); And see what you are getting. –  Nick M Nov 14 '13 at 5:38
    
Simply don't convert the data. –  Felix Kling Nov 14 '13 at 5:41
    
["block","block","block","block","block","block","block","block","block","block"‌​,"block","block","block","block","block","block","block","block","block","block"] Its missing the numbers.. "0":"block","1":"block"... –  Christine Wilson Nov 14 '13 at 5:47

4 Answers 4

up vote 17 down vote accepted

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:

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:

{"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

share|improve this answer
    
OMG! Thank you :) –  Christine Wilson Nov 14 '13 at 5:54
    
So you do all this.. then you don't convert anything! data: display2, dataType: "json" and it all works –  Christine Wilson Nov 14 '13 at 5:55
    
When you work with objectw and have numeric index, then you don't have to put them in quotes. i.e. display2[0] = "none" is enough –  instead Mar 3 at 12:17

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

share|improve this answer
    
This works really well. Thank you for sharing this solution. –  Ty Bailey Jul 14 at 13:57
    
works like magic –  giorgio79 Aug 17 at 14:23

here is the other way with example

        var name = $("#fullname").val();
        var age = $("#age").val();
        var email = $("#email").val();
        var city = $("#city").data("kendoComboBox");
        var date = $("#date").val();



        var Data = JSON.stringify({ Name: name, Age: age, Email: email, City: city.text(), Date: date });

        alert(Data);


        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'RegFrm.aspx/InsertMethod',
            // data: "{'Name':'" + document.getElementById('fullname').value + "', 'Age':'" + document.getElementById('age').value + "'}",      
            data: Data,
            async: false,

            success: function (response) {
                alert("Record Has been Saved in Database");
            },

            error: function ()
            { console.log('there is some error'); }
        });
share|improve this answer
    
Thank DjAdmin. I find it easier to pass separate fields and then JSON stringify. It's when I need to use an array, this stops working. I realized I needed to use an object and not an array in the end. –  Christine Wilson Nov 14 '13 at 22:22
    
can u make my answer vote ? –  LittleDragon Aug 6 at 6:41

You can do var Content = JSON.parse(rsp);

share|improve this answer
    
The parse method takes a string and parses it into an object or array. The op has an array already. –  Guffa Nov 14 '13 at 5:43
    
Ah yes my mistake... –  Jayantha Nov 14 '13 at 5:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.