Module that attempts to parse string values of an object into JSON.
Install the module with: npm install lame-json
Sometimes JSON comes back with values as a string.
{
"foo": "true",
"bar": "123",
"baz": "{\"hello\":\"world\"}",
"qux": "[ 1, 2, 3 ]"
}In some cases, these values are meant to be parsed into primitives or native JS objects:
{
foo: true,
bar: 123,
baz: {
"hello": "world"
},
qux: [ 1, 2, 3 ]
}This module helps you do that.
Usage is very straight forward:
var lameJson = require('lame-json');
var data = {
"foo": "true",
"bar": "123",
"baz": "{\"hello\":\"world\"}"
}
var newData = lameJson.parseJson(data);
/*
=> {
foo: true,
bar: 123,
baz: {
"hello": "world"
}
}
*/If a value cannot be parsed out of the string, the original value is returned:
var newData = lameJson.parseJson({
"foo": "[ 1, 2, 3 }"
});
// => { "foo": "[ 1, 2, 3 }" }If you want to parse a specific string value:
var newData = lameJson.parse('[1, 2, 3]');
// => [1, 2, 3]If you want to parse many times using the same options, you can use the factory method returned by the module. The factory method accepts a set of options, which are then used to create a parser object that always uses those options:
var parser = lameJson({
boolean: false
});
parser.parse('[1, 2, 3]');
// => [1, 2, 3]
parser.parse('false');
// => 'false'
parser.parseJson({
"foo": "true",
"bar": "123",
});
/*
=> {
foo: 'true',
bar: 123,
}
*/Creates a lameJson parser object that alwayhs uses the passed in options. If you only need to use the functions once or twice, you can use the static functions documented below.
options.boolean{Boolean} - If true, parses booleans. Defaults to true.options.float{Boolean} - If true, parses ints and floats. Defaults to true. This only works when the full string is used during parsing (e.g123foowould be ignored)options.exponential{Boolean} - If true, parses exponential numbers such as2e2. Defaults to false. This only works when the full string is used during parsing (e.g2e2foowould be ignored)options.array{Boolean} - If true, attempts parse arrays. Defaults to true.options.object{Boolean} - If true, attempts to parse objects. Defaults to true.
Returns: {Object} a parser object with two methods, parseJson and parse
Try to parse string values out of JSON values. You can use this in place of
JSON.parse(). Options are the same as above.
Returns: {Object} a new object with possibly parsed values.
Try to parse a possible value out of a string. This is the underlying
implementation used by parseJson(). Options are the same as above.
Returns: {Object} a new object with possibly parsed values.
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality.
To start contributing, install the git pre-push hooks:
make githooksBefore committing, lint and test your code:
make prepushCopyright (c) 2018 Alex Liu.
Licensed under the MIT license.