devalue
Gets the job done when JSON.stringify can't
README
devalue
Like JSON.stringify, but handles
- cyclical references (obj.self = obj)
- repeated references ([value, value])
- undefined, Infinity, NaN, -0
- regular expressions
- dates
- Map and Set
- BigInt
- custom types via replacers, reducers and revivers
Try it out here.
Goals:
- Performance
- Security (see XSS mitigation)
- Compact output
Non-goals:
- Human-readable output
- Stringifying functions
Usage
There are two ways to use devalue:
uneval
This function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like eval in reverse:
- ```js
- import * as devalue from 'devalue';
- let obj = { message: 'hello' };
- devalue.uneval(obj); // '{message:"hello"}'
- obj.self = obj;
- devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'
- ```
Use uneval when you want the most compact possible output and don't want to include any code for parsing the serialized value.
stringify and parse
These two functions are analogous to JSON.stringify and JSON.parse:
- ```js
- import * as devalue from 'devalue';
- let obj = { message: 'hello' };
- let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
- devalue.parse(stringified); // { message: 'hello' }
- obj.self = obj;
- stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
- devalue.parse(stringified); // { message: 'hello', self: [Circular] }
- ```
Use stringify and parse when evaluating JavaScript isn't an option.
unflatten
In the case where devalued data is one part of a larger JSON string, unflatten allows you to revive just the bit you need:
- ```js
- import * as devalue from 'devalue';
- const json = `{
- "type": "data",
- "data": ${devalue.stringify(data)}
- }`;
- const data = devalue.unflatten(JSON.parse(json).data);
- ```
Custom types
You can serialize and serialize custom types by passing a second argument to stringify containing an object of types and their _reducers_, and a second argument to parse or unflatten containing an object of types and their _revivers_:
- ```js
- class Vector {
- constructor(x, y) {
- this.x = x;
- this.y = y;
- }
- magnitude() {
- return Math.sqrt(this.x * this.x + this.y * this.y);
- }
- }
- const stringified = devalue.stringify(new Vector(30, 40), {
- Vector: (value) => value instanceof Vector && [value.x, value.y]
- });
- console.log(stringified); // [["Vector",1],[2,3],30,40]
- const vector = devalue.parse(stringified, {
- Vector: ([x, y]) => new Vector(x, y)
- });
- console.log(vector.magnitude()); // 50
- ```
If a function passed to stringify returns a truthy value, it's treated as a match.
You can also use custom types with uneval by specifying a custom replacer:
- ```js
- devalue.uneval(vector, (value, uneval) => {
- if (value instanceof Vector) {
- return `new Vector(${value.x},${value.y})`;
- }
- }); // `new Vector(30,40)`
- ```
Note that any variables referenced in the resulting JavaScript (like Vector in the example above) must be in scope when it runs.
Error handling
If uneval or stringify encounters a function or a non-POJO that isn't handled by a custom replacer/reducer, it will throw an error. You can find where in the input data the offending value lives by inspecting error.path:
- ```js
- try {
- const map = new Map();
- map.set('key', function invalid() {});
- uneval({
- object: {
- array: [map]
- }
- });
- } catch (e) {
- console.log(e.path); // '.object.array[0].get("key")'
- }
- ```
XSS mitigation
Say you're server-rendering a page and want to serialize some state, which could include user input. JSON.stringify doesn't protect against XSS attacks:
- ```js
- const state = {
- userinput: `</script>