You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.2 KiB

var bops = require('bops')
12 years ago
12 years ago
//TODO: handle reviver/dehydrate function like normal
//and handle indentation, like normal.
//if anyone needs this... please send pull request.
12 years ago
12 years ago
exports.stringify = function stringify (o) {
if(o && bops.is(o))
return JSON.stringify(':base64:' + bops.to(o, 'base64'))
12 years ago
if(o && o.toJSON)
o = o.toJSON()
12 years ago
if(o && 'object' === typeof o) {
var s = ''
var array = Array.isArray(o)
s = array ? '[' : '{'
var first = true
for(var k in o) {
var isFunction = 'function' == typeof o[k]
if(Object.hasOwnProperty.call(o, k) && o[k] !== void(0) && !isFunction) {
12 years ago
if(!first)
s += ','
12 years ago
first = false
s += array ? stringify(o[k]) : stringify(k) + ':' + stringify(o[k])
12 years ago
}
}
s += array ? ']' : '}'
return s
} else if ('string' === typeof o) {
return JSON.stringify(/^:/.test(o) ? ':' + o : o)
} else
12 years ago
return JSON.stringify(o)
}
exports.parse = function (s) {
return JSON.parse(s, function (key, value) {
if('string' === typeof value) {
if(/^:base64:/.test(value))
return bops.from(value.substring(8), 'base64')
else
return /^:/.test(value) ? value.substring(1) : value
}
12 years ago
return value
})
}