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:

  1. ```js
  2. import * as devalue from 'devalue';

  3. let obj = { message: 'hello' };
  4. devalue.uneval(obj); // '{message:"hello"}'

  5. obj.self = obj;
  6. devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'
  7. ```

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:

  1. ```js
  2. import * as devalue from 'devalue';

  3. let obj = { message: 'hello' };

  4. let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
  5. devalue.parse(stringified); // { message: 'hello' }

  6. obj.self = obj;

  7. stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
  8. devalue.parse(stringified); // { message: 'hello', self: [Circular] }
  9. ```

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:

  1. ```js
  2. import * as devalue from 'devalue';

  3. const json = `{
  4.   "type": "data",
  5.   "data": ${devalue.stringify(data)}
  6. }`;

  7. const data = devalue.unflatten(JSON.parse(json).data);
  8. ```

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_:

  1. ```js
  2. class Vector {
  3. constructor(x, y) {
  4.   this.x = x;
  5.   this.y = y;
  6. }

  7. magnitude() {
  8.   return Math.sqrt(this.x * this.x + this.y * this.y);
  9. }
  10. }

  11. const stringified = devalue.stringify(new Vector(30, 40), {
  12. Vector: (value) => value instanceof Vector && [value.x, value.y]
  13. });

  14. console.log(stringified); // [["Vector",1],[2,3],30,40]

  15. const vector = devalue.parse(stringified, {
  16. Vector: ([x, y]) => new Vector(x, y)
  17. });

  18. console.log(vector.magnitude()); // 50
  19. ```

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:

  1. ```js
  2. devalue.uneval(vector, (value, uneval) => {
  3. if (value instanceof Vector) {
  4.   return `new Vector(${value.x},${value.y})`;
  5. }
  6. }); // `new Vector(30,40)`
  7. ```

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:

  1. ```js
  2. try {
  3. const map = new Map();
  4. map.set('key', function invalid() {});

  5. uneval({
  6.   object: {
  7.    array: [map]
  8.   }
  9. });
  10. } catch (e) {
  11. console.log(e.path); // '.object.array[0].get("key")'
  12. }
  13. ```

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:

  1. ```js
  2. const state = {
  3. userinput: `</script>