Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2014
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. stringify({ data: { hello: 'world', with: { nested: 'objects' } } })
  2.  
  3. {
  4. "data": {
  5. "hello": "world",
  6. "with": {
  7. "nested": "objects"
  8. }
  9. }
  10. }
  11.  
  12. function stringify(object, indentation) {
  13. if (typeof indentation === 'undefined') {
  14. indentation = 0;
  15. }
  16.  
  17. var items = [];
  18.  
  19. for (var key in object) {
  20. if (object.hasOwnProperty(key)) {
  21. var value;
  22.  
  23. switch (typeof object[key]) {
  24. case 'object':
  25. var type = Object.prototype.toString.call(object[key]);
  26.  
  27. switch (type) {
  28. case '[object Null]':
  29. value = 'null';
  30. break;
  31.  
  32. case '[object Array]':
  33. case '[object Object]':
  34. value = stringify(object[key], indentation + 2);
  35. break;
  36.  
  37. default:
  38. value = type;
  39. }
  40. break;
  41.  
  42. case 'string':
  43. value = '"' + object[key] + '"'
  44. break;
  45.  
  46. default:
  47. value = object[key];
  48. }
  49.  
  50. items.push(Array(indentation + 3).join(' ') + '"' + key + '": ' + value);
  51. }
  52. }
  53.  
  54. return '{n'
  55. + items.join(',n') + 'n'
  56. + Array(indentation + 1).join(' ') + '}';
  57. }
  58.  
  59. // Example:
  60. console.log(stringify({ data: { hello: 'world', with: { nested: 'objects' } } }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement