json-paths
Collect different paths of JSON data. Allows to compare complex JSON structures by it's shape.
Installation
Install from npm:
npm install json-pathsUsage
Import jsonPaths and call it on some JSON data:
import { jsonPaths } from 'json-paths';
// given some data
const data = {
foo: {
bar: 'aaa',
baz: 'bbb',
}
};
// calculate json paths
const shape = jsonPaths(data);
/*
{
'foo.bar': 1,
'foo.baz': 1
}
*/For arrays, all elements are counted with the same path and # as an index:
const data = {
foo: {
bar: ['a', 'b', 'c']
}
};
const shape = jsonPaths(data);
/*
{
'foo.bar.#': 3
}
*/You can count each value inside a path:
const data = {
foo: {
bar: ['a', 'a', 'a', 'b', 'c']
}
};
const shape = jsonPaths(data, { '*': 'value' });
/*
{
'foo.bar.#': {
a: 3,
b: 1,
c: 1,
}
}
*/Ignoring path:
const data = {
foo: {
bar: 'aaa',
baz: 'bbb',
}
};
const shape = jsonPaths(data, { 'foo.bar': false });
/*
{
'foo.baz': 1,
}
*/API
jsonPaths(obj, rules?, options?)
Params
objobject | array - JSON data to calculate pathsrulesobject - rules for calculating different paths. Each key in that object serves as a path prefix (*matches any path). Each value is one of the following:- any falsy value - path is ignored
"value"- calculates count for each value in that path- function - the same as
"value", but value is transformed by the function - any other value - calculates count of that path (default)
optionsobject - additional optionssepstring - path separator (default.)sepReplacementstring - replacement ifsepis found in original object key (default~)indexReplacementstring - replacement for array indexes (default#)
Returns: object - object with json paths