diff --git a/README.md b/README.md index a11f302..736ed85 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # json-stringify-safe -Like JSON.stringify, but doesn't throw on circular references. +Like JSON.stringify, but doesn't throw on circular references and BigInt values. ## Usage @@ -11,6 +11,7 @@ var stringify = require('json-stringify-safe'); var circularObj = {}; circularObj.circularRef = circularObj; circularObj.list = [ circularObj, circularObj ]; +circularObj.bigint = 1n; console.log(stringify(circularObj, null, 2)); ``` @@ -22,7 +23,8 @@ Output: "list": [ "[Circular]", "[Circular]" - ] + ], + "bigint": "1" } ``` @@ -41,6 +43,8 @@ will prune cycles. If you pass in `function(k,v){ return {foo: 'bar'}}`, then cyclical objects will always be represented as `{"foo":"bar"}` in the result. +`BigInt` values are serialized as strings. + ``` stringify.getSerialize(serializer, decycler) ``` diff --git a/package.json b/package.json index 4ab27ed..3de2ae5 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,20 @@ { "name": "json-stringify-safe", - "version": "5.0.1", - "description": "Like JSON.stringify, but doesn't blow up on circular refs.", + "version": "5.1.0", + "description": "Like JSON.stringify, but doesn't blow up on circular refs and BigInts.", "keywords": [ "json", "stringify", "circular", - "safe" + "safe", + "bigint" ], "homepage": "https://github.com/isaacs/json-stringify-safe", "bugs": "https://github.com/isaacs/json-stringify-safe/issues", "author": "Isaac Z. Schlueter (http://blog.izs.me)", "contributors": [ - "Andri Möll (http://themoll.com)" + "Andri Möll (http://themoll.com)", + "Luka Maljic (https://codecraft.dev)" ], "license": "ISC", "repository": { diff --git a/stringify.js b/stringify.js index 124a452..4a9d196 100644 --- a/stringify.js +++ b/stringify.js @@ -22,6 +22,8 @@ function serializer(replacer, cycleReplacer) { } else stack.push(value) + if (typeof value === "bigint") value = value.toString() + return replacer == null ? value : replacer.call(this, key, value) } } diff --git a/test/stringify_test.js b/test/stringify_test.js index 5b32583..3d4f414 100644 --- a/test/stringify_test.js +++ b/test/stringify_test.js @@ -98,6 +98,19 @@ describe("Stringify", function() { json.must.eql(jsonify([{name: "Alice"}, {name: "Alice"}])) }) + it("must stringify BigInts", function() { + var bigint = 1n + var json = stringify(bigint, null, 2) + json.must.eql(jsonify("1")) + }) + + it("must stringify circular objects with BigInts", function() { + var obj = {n: 1n} + obj.identity = {self: obj} + var json = stringify(obj, null, 2) + json.must.eql(jsonify({n: "1", identity: {self: "[Circular ~]"}})) + }) + it("must call given decycler and use its output", function() { var obj = {} obj.a = obj