greatjson

JSON.parse replacement with clearer Syntax messages providing location, expected tokens and offending text. Errors are returned, not thrown. By Harald Rudell

npm install greatjson
3 downloads in the last week
58 downloads in the last month

Great Json

The greatjson module is a JSON.parse replacement providing clearer syntax messages with line and column numbers, expected tokens and offending text. In addition, errors are returned instead of thrown.

Get It Now

Usage

Example of parsing with greatjson:

var greatjson = require('greatjson')
var result, error

// example how to use successfully
if (!((result = greatjson.parse('17')) instanceof Error))
    // It works! I got: 17
    console.log('It works! I got:', result)

// example of parse failure
if (!((error = greatjson.parse('qwerty')) instanceof Error)) ;
else
    // SyntaxError: Unexpected token: expected json value, text:'qwerty' at line:1 column:1 position: 0 (0%)
    console.log(error.toString())

// example of missing comma
if (!((error = greatjson.parse('{"a":5"b":6}')) instanceof Error)) ;
else {
    // SyntaxError: Bad token: expected object comma, text:'"b":6.' at line:1 column:7 position: 6 (50%)
    console.log(error.toString())

    // printout of custom error properties
    var s = []
    for (var p in error) s.push(p + ':' + error[p])
    // Error properties: position:6 line:1 column:7 text:"b":6.
    console.log('Error properties:', s.join(' '))
}

Notes

(c) Harald Rudell wrote this for the love of node in August, 2012

Great Json is based on work by

JavaScript Object Notation or json is a language-independent text format.

rfc4627: the application/json media type.

JSON.parse in secion 15.12.2 of JavaScript.

No warranty expressed or implied. Use at your own risk.

Please suggest better ways, new features, and possible difficulties on github

npm loves you