@ambassify/json-parse-safe

1.1.0 • Public • Published

json-parse-safe

Like JSON.parse, but doesn't throw on invalid JSON.

Usage

Takes the same arguments as JSON.parse.

const parse = require('json-parse-safe');
const validJson = '{ "foo": "bar" }';
const invalidJson = 'foo';

// Simple usage
console.log(parse(validJson)); // { foo: 'bar' }
console.log(parse(invalidJson)); // null

// Pass a reviver just like the real JSON.parse
parse('{"p": 5}', (key, value) =>
  typeof value === 'number'
    ? value * 2 // return value * 2 for numbers
    : value     // return everything else unchanged
);
// { p: 10 }

// choose a defaultValue for invalid json
console.log(parse(invalidJson, undefined, 'WHOOPS')); // 'WHOOPS'

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.1.0
    35
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.1.0
    35
  • 1.0.0
    0

Package Sidebar

Install

npm i @ambassify/json-parse-safe

Weekly Downloads

35

Version

1.1.0

License

MIT

Unpacked Size

1.6 kB

Total Files

3

Last publish

Collaborators

  • ambassify
  • jorgenevens
  • sitebase