Convert strings representing paths or objects with a path and optional value to a JSON object.
$ npm install jsonify-paths
const jsonifyPaths = require('jsonify-paths');
jsonifyPaths.from('a/bb/ccc');
// =>
{
"a": {
"bb": {
"ccc": {}
}
}
}
jsonifyPaths.from([
'I am/not/a number',
'I am/a/free man!'
]);
// =>
{
"I am": {
"not": {
"a number": {}
},
"a": {
"free man!": {}
}
}
}
jsonifyPaths.from({path: 'a/bb/ccc'});
// =>
{
"a": {
"bb": {
"ccc": {}
}
}
}
Providing value
jsonifyPaths.from({path: 'a/bb/ccc', value: 'foo'});
// =>
{
"a": {
"bb": {
"ccc": "foo"
}
}
}
jsonifyPaths.from([
{path: 'a/bb/ccc'},
{path: 'a/bb/d'},
{path: 'e'},
]);
// =>
{
"a": {
"bb": {
"ccc": {},
"d": {}
}
},
"e": {}
}
Providing values (optional)
jsonifyPaths.from([
{path: 'a/bb/ccc', value: "foo"},
{path: 'a/bb/d'},
{path: 'e', value: false},
{path: 'f/g', value: ""}
{path: 'f/h', value: 123}
]);
// =>
{
"a": {
"bb": {
"ccc": "foo",
"d": {} // => default value
}
},
"e": false,
"f": {
"g": "",
"h": 123
}
}
jsonifyPaths.from('a>bb>ccc', {delimiter: '>'});
jsonifyPaths.from('a|bb|ccc', {delimiter: '|'});
jsonifyPaths.from('a»-»bb»-»ccc', {delimiter: '»-»');
jsonifyPaths.from('a/b/c');
jsonifyPaths.from('/a/b/c');
jsonifyPaths.from('/a/b/c/');
jsonifyPaths.from('//a/b//c');
jsonifyPaths.from('/a / b/ c /');
jsonifyPaths.from('/ a //b / c///');
// =>
{
"a": {
"b": {
"c": {}
}
}
}
jsonifyPaths.from({path: 'Lyon ✈ Reykjavik ✈ Vienna', value:"On Time"}, {delimiter: '✈'});
// =>
{
"Lyon": {
"Reykjavik": {
"Vienna": "On Time"
}
}
}
Forcing option to false
jsonifyPaths.from('I / am not a / number', {ignoreSpacesAroundDelimiters: false});
// =>
'I ': {
' am not a ': {
' number': {}
}
}
Default value is used when value is not set for an object
jsonifyPaths.from([
{path: 'Lyon ✈ Berlin ✈ Rome'},
{path: 'Lyon ✈ Berlin ✈ Geneva', value: "On Time"},
{path: 'Bangkok ✈ Tokyo', value: "Delayed"},
], {delimiter: '✈', defaultValue: 'Scheduled'});
// =>
{
"Lyon": {
"Berlin": {
"Rome": "Scheduled", // => default value
"Geneva": 'On Time'
}
},
"Bangkok": {
"Tokyo": 'Delayed'
}
};
const res = jsonifyPaths.from([
{path: 'Lyon ✈ Berlin ✈ Rome'},
'Lyon ✈ Paris',
'Bangkok ✈ Tokyo',
{path: 'Lyon ✈ Berlin ✈ Geneva', value: 'On Time'},
], {delimiter: '✈', defaultValue: 'Scheduled'});
// =>
{
"Lyon": {
"Berlin": {
"Rome": "Scheduled",
"Geneva": "On Time"
},
"Paris": "Scheduled"
},
"Bangkok": {
"Tokyo": "Scheduled"
}
}