omnibelt/json-parse-safe.js

  1. const pipe = require('ramda/src/pipe');
  2. const list = require('./list');
  3. const tryCatchSafe = require('./try-catch-safe');
  4. /**
  5. * A safe version of `JSON.parse` that returns an [error, result] tuple instead
  6. * of throwing an error.
  7. *
  8. * @signature * -> Array<?SyntaxError, *>
  9. *
  10. * @example
  11. * const [error, result] = jsonParseSafe('{ "foo": "bar" }'); // => [null, { foo: 'bar' }]
  12. * const [error, result] = jsonParseSafe('{'); // => [SyntaxError, null]
  13. */
  14. const jsonParseSafe = pipe(
  15. list,
  16. tryCatchSafe(JSON.parse)
  17. );
  18. module.exports = jsonParseSafe;