Get and Set values in JSON objects using keypaths
sh
npm install --save json-keypath
`
Usage
Older Versions:
`js
var JSONKeyPath = require('json-keypath');
`
ES6 and above:
Directly import specific method with object spread
`js
import { setValue, getValue } from 'json-keypath';
`
Example
`js
var JSONKeyPath = require('json-keypath');
var data = {
example: {
app: {
count: 5
}
}
}
var value = JSONKeyPath.getValue(data, 'example.app.count');
console.log(value); // 5
JSONKeyPath.setValue(data, 'example.app.count', 6);
value = JSONKeyPath.getValue(data, 'example.app.count');
console.log(value); // 6
`
You can set values by creating new path too.
`js
JSONKeyPath.setValue(data, 'example.app.label', 'likes');
value = JSONKeyPath.getValue(data, 'example.app.label');
console.log(value); // likes
`
To avoid creating new paths, pass true as the last parameter
`js
JSONKeyPath.setValue(data, 'example.app.label', 'likes', true);
value = JSONKeyPath.getValue(data, 'example.app.label');
// error Invalid path
`
By default, passing an invalid path to get would return undefined. To follow strict path, pass the last parameter as true
`js
var value = JSONKeyPath.getValue(data, 'example.app.views');
console.log(value); // undefined
var value = JSONKeyPath.getValue(data, 'example.app.views', true);
// error Invalid path
``