Awesome json2json
An awesome json to json mapper
Installation
npm install awesome-json2json --save
Usage
import json2json from 'awesome-json2json';
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: 'foo.bar.baz'
});
Template
Template is the structure of your output json, the rule of how to map one json data to another. The syntax should look like this:
{
new_foo1: 'foo.bar.baz',
new_foo2: 'foo.not_exist_key?.bar.baz',
new_foo3: (root) => { return root.foo.bar.baz; },
new_foo4: {
$path: 'foo',
$formatting: (foo) => { return foo.bar.baz; }
},
new_foo5: {
$path: 'foo',
new_bar1: 'bar.baz',
new_bar2: '$root.foo.bar.baz',
new_bar3: {
$formatting: (foo) => { return foo.bar.baz; }
},
new_bar4: {
$disable: (foo) => { return foo.bar.baz === 1; }
new_baz: 'foo.bar.baz'
},
},
new_foo_array1: 'foo_array[].bar',
new_foo_array2: {
$path: 'foo_array[]',
$formatting: (foo_item) => { return foo_item.bar; }
}
}
Features
Optional chaining
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: 'foo.not_exist_key?.bar.baz'
});
Function template
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: (root) => {
return root.foo.bar.baz + '_formatted';
}
});
Template with $path and $formatting
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: {
$path: 'foo.bar',
$formatting: (bar) => {
return bar.baz + '_formatted';
}
}
});
Nested template
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: {
$path: 'foo',
new_bar: 'bar.baz'
}
});
Nested template with $path and $formatting
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: {
$path: 'foo',
$formatting: (foo) => {
return {
baz2: foo.bar.baz + '_formatted'
}
},
new_bar: 'baz2'
}
});
Nested template with $disable
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: {
$path: 'foo',
new_bar1: {
$disable: (foo) => {
return foo.bar.baz === 1;
},
new_baz: 'bar.baz'
},
new_bar2: 'bar.baz'
}
});
Template with $root
json2json({ foo: { bar: { baz: 1 }}}, {
new_foo: {
$path: 'foo',
new_bar: {
$path: 'bar',
new_baz1: 'baz',
new_baz2: '$root.foo'
}
}
});
Array template
json2json({
foo: [
{ bar: 1 },
{ bar: 2 },
{ bar: 3 }
]
}, {
new_foo: 'foo[].bar'
});
Array template with $formatting
json2json({
foo: [
{ bar: 1 },
{ bar: 2 },
{ bar: 3 }
]
}, {
new_foo: {
$path: 'foo[].bar',
$formatting: (barValue) => barValue + '_formatted'
}
});
Nested array template
json2json({
foo: [
{ bar: 1 },
{ bar: 2 },
{ bar: 3 }
]
}, {
new_foo: {
$path: 'foo[]',
new_bar: {
$formatting: (fooItem) => {
return fooItem.bar;
}
}
}
});
Clear all empty data
Passing clearEmpty: true
to the third parameter of json2json
will clear all empty data including undefined
, null
, empty object {}
, empty array []
, and combination of empty object and empty array such as [{}, {}, {}]
json2json({
foo: [
{ bar: 1 },
{ bar: 2 },
{ bar: 3 }
]
}, {
new_foo: {
new_bar1: 'foo[].bar',
new_bar2: {
$path: 'foo[]',
new_baz1: 'baz',
new_baz2: {
new_qux: 'baz'
}
}
}
}, {
clearEmpty: true
});