Created
June 19, 2014 04:41
-
-
Save ishiduca/51ce02b927fbb11af78e to your computer and use it in GitHub Desktop.
循環参照を含むオブジェクトのJSON.stringify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function (global) { | |
'use strict' | |
var isBrowser = !! global.self | |
var isWorker = !! global.workerLocation | |
var isNodeJS = !! global.global | |
function stringify (o, rep, sp) { | |
return JSON.stringify(o, (function (m) { | |
return function (key, val) { | |
if (val instanceof Error) return val.toString() | |
if (indexOf(m, val) !== -1) return '[Circular]' | |
val && 'object' === typeof val && m.push(val) | |
return 'function' === typeof rep ? rep(key, val) : val | |
} | |
})([]), sp) | |
} | |
function indexOf (arry, target) { | |
if ('function' === typeof arry.indexOf) return arry.indexOf(target) | |
for (var i = 0, len = arry.length; i < len; i++) { | |
if (arry[i] === target) return i | |
} | |
return -1 | |
} | |
if (isNodeJS) { | |
module.exports.stringify = stringify | |
} else { | |
global['Message'] = { | |
stringify: stringify | |
} | |
} | |
})(this.self || global) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var test = require('tape') | |
var mod | |
var circular = '[Circular]' | |
test('load module', function (t) { | |
mod = require('..') | |
t.ok(mod, 'var mod = require("..")') | |
t.is(typeof mod.stringify, 'function', 'typeof mod.stringify === "function"') | |
t.end() | |
}) | |
test('循環参照しているプロパティは 文字列 "' + circular + '" に置き換わる', function (t) { | |
var obj = {a: 3} | |
obj.self = obj | |
obj.list = [obj, obj] | |
var testObj = { | |
a: 3 | |
, self: circular | |
, list: [circular, circular] | |
} | |
t.is(JSON.stringify(testObj, null, 2) | |
, mod.stringify(obj, null, 2) | |
, mod.stringify(obj, null, 2) | |
) | |
t.end() | |
}) | |
test('エラーオブジェクトは "name: message" に置き換わる', function (t) { | |
var e = new TypeError('oh no!') | |
var obj = {error: e} | |
t.is(mod.stringify(obj) | |
, '{"error":"TypeError: oh no!"}' | |
, mod.stringify(obj) | |
) | |
t.end() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment