index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //TODO: handle reviver/dehydrate function like normal
  2. //and handle indentation, like normal.
  3. //if anyone needs this... please send pull request.
  4. exports.stringify = function stringify (o) {
  5. if('undefined' == typeof o) return o
  6. if(o && Buffer.isBuffer(o))
  7. return JSON.stringify(':base64:' + o.toString('base64'))
  8. if(o && o.toJSON)
  9. o = o.toJSON()
  10. if(o && 'object' === typeof o) {
  11. var s = ''
  12. var array = Array.isArray(o)
  13. s = array ? '[' : '{'
  14. var first = true
  15. for(var k in o) {
  16. var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])
  17. if(Object.hasOwnProperty.call(o, k) && !ignore) {
  18. if(!first)
  19. s += ','
  20. first = false
  21. if (array) {
  22. if(o[k] == undefined)
  23. s += 'null'
  24. else
  25. s += stringify(o[k])
  26. } else if (o[k] !== void(0)) {
  27. s += stringify(k) + ':' + stringify(o[k])
  28. }
  29. }
  30. }
  31. s += array ? ']' : '}'
  32. return s
  33. } else if ('string' === typeof o) {
  34. return JSON.stringify(/^:/.test(o) ? ':' + o : o)
  35. } else if ('undefined' === typeof o) {
  36. return 'null';
  37. } else
  38. return JSON.stringify(o)
  39. }
  40. exports.parse = function (s) {
  41. return JSON.parse(s, function (key, value) {
  42. if('string' === typeof value) {
  43. if(/^:base64:/.test(value))
  44. return new Buffer(value.substring(8), 'base64')
  45. else
  46. return /^:/.test(value) ? value.substring(1) : value
  47. }
  48. return value
  49. })
  50. }