Posted By

coder_ on 02/10/11


Tagged

javascript array json


Versions (?)

Array2json


 / Published in: JavaScript
 

  1. function array2json(arr) {
  2. var parts = [];
  3. var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
  4.  
  5. for(var key in arr) {
  6. var value = arr[key];
  7. if(typeof value == "object") { //Custom handling for arrays
  8. if(is_list) parts.push(array2json(value));
  9. else parts[key] = array2json(value);
  10. } else {
  11. var str = "";
  12. if(!is_list) str = '"' + key + '":';
  13.  
  14. //Custom handling for multiple data types
  15. if(typeof value == "number") str += value; //Numbers
  16. else if(value === false) str += 'false'; //The booleans
  17. else if(value === true) str += 'true';
  18. else str += '"' + value + '"'; //All other things
  19. // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
  20.  
  21. parts.push(str);
  22. }
  23. }
  24. var json = parts.join(",");
  25.  
  26. if(is_list) return '[' + json + ']';//Return numerical JSON
  27. return '{' + json +
  28. '}';//Return associative JSON
  29. }

Report this snippet  

You need to login to post a comment.