Convert javascript object or array to json for ajax data

So, I create an array with information about the element. I go through all the elements and keep 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 am trying to turn it into a JSON object:

 data = JSON.stringify(display); 

It does not seem to send the correct JSON format!

If I pass the code like this, it works and sends the 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 make a warning in a JSON.stringify object, it looks the same as a manual encoded one. But that will not work.

I'm going crazy trying to solve this! What am I missing here? What is the best way to send this information to get a manual encoding format?

I use 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 the GET method because I display information (without updating or pasting). Transferring information only to my php file.




END OF DECISION




 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 ); } }); 
+32
json javascript arrays stringify
Nov 14 '13 at 5:35
source share
2 answers

I'm not quite sure, but I think you are probably surprised at how arrays are serialized in JSON. Let isolate the problem. Consider the 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 the array. However, what you want to see is something like:

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

To get this format, you want to serialize the object, not the array. Therefore, rewrite the code above as follows:

 var display2 = {}; display2["0"] = "none"; display2["1"] = "block"; display2["2"] = "none"; console.log( JSON.stringify(display2) ); 

This will print in the desired format.

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

+68
Nov 14
source share

You can use JSON.stringify(object) with the object, and I just wrote a function that will recursively convert the array to an object like this JSON.stringify(convArrToObj(array)) , which is the following code (more detailed information 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 universal, you can override the JSON.stringify function, and you no longer have to worry about it, to do this, just paste it at the top of the 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 an example )




Edit:

Here is another version that is slightly more efficient, although it may or may not be less reliable (not sure - it depends on whether JSON.stringify(array) always returns [] that I don’t see many reasons why this will not be, therefore this function should be better, since it works a little less when you use JSON.stringify with 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 an example here

js performance test here through jsPerf

+15
Jul 14 '14 at 1:43
source share



All Articles