Home

Awesome

try-read-json npmjs.com The MIT License npm downloads

Graceful reading of JSON value, using JSON.parse with support for optional callback

code climate standard code style travis build status coverage status dependency status

Install

Install with npm

$ npm i try-read-json --save

Usage

For more use-cases see the tests

const tryReadJson = require('try-read-json')

API

tryReadJson

Parses input JSON value without throwing an errors.

Params

Example

var tryReadJson = require('try-read-json')

// synchronous
console.log(tryReadJson(1234)) // => 1234
console.log(tryReadJson('1234')) // => 1234
console.log(tryReadJson('["aaa", "bbb"]')) // => [ 'aaa', 'bbb' ]
console.log(tryReadJson('{"foo": "bar"}')) // => { foo: 'bar' }
console.log(tryReadJson(null)) // => null
console.log(tryReadJson(true)) // => true
console.log(tryReadJson(false)) // => false

console.log(tryReadJson()) // => SyntaxError
console.log(tryReadJson(undefined)) // => SyntaxError
console.log(tryReadJson('{"foo:bxbba')) // => SyntaxError

// with callback
tryReadJson('{"foo":"bar"}', function cb (err, obj) {
  console.log(err, obj) // => null, { foo: 'bar' }
})

tryReadJson(123, function cb (err, num) {
  console.log(err, num) // => null, 123
})

tryReadJson('["aaa", "bbb"]', function cb (err, arr) {
  console.log(err, arr) // => null, [ 'aaa', 'bbb' ]
  console.log(arr[0]) // => 'aaa'
  console.log(arr[1]) // => 'bbb'
})

tryReadJson('{foo fail', function cb (err) {
  console.log(err) // => SyntaxError
})

tryReadJson(undefined, function cb (err) {
  console.log(err) // => SyntaxError
})

tryReadJson(true, function cb (err, bool) {
  console.log(err, bool) // => null, true
})

Related

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
But before doing anything, please read the CONTRIBUTING.md guidelines.

Charlike Make Reagent new message to charlike freenode #charlike

tunnckoCore.tk keybase tunnckoCore tunnckoCore npm tunnckoCore twitter tunnckoCore github