json-keypath

0.1.2 • Public • Published

json-keypath

Get and Set values in JSON objects using keypaths

Install

npm install --save json-keypath

Usage

Older Versions:

var JSONKeyPath = require('json-keypath');
 

ES6 and above:

Directly import specific method with object spread

import { setValue, getValue } from 'json-keypath';
 

Example

 
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.

 
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

 
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

 
var value = JSONKeyPath.getValue(data, 'example.app.views');
console.log(value); // undefined
 
var value = JSONKeyPath.getValue(data, 'example.app.views', true);
// error Invalid path
 

Contributing

Contributions are welcome!

Fork this repo, clone it locally, Submit a pull request once you are done with your changes

License

MIT

Package Sidebar

Install

npm i json-keypath

Weekly Downloads

7

Version

0.1.2

License

MIT

Unpacked Size

4.48 kB

Total Files

4

Last publish

Collaborators

  • jefreesujit