jsonremap
v1.1.7
Published
Flattens any JSON structure with ability to rename fields and array support
Downloads
68
Readme
JSON Remap
Flattens any JSON structure with ability to rename fields.
Handles arrays and normalizes data.
Best suitable for CSV preparing.
Install
Use NPM:
$ npm install jsonremap
or Mercurial:
$ hg clone ssh://[email protected]/andreyh/jsonremap
Usage example
const JSONRemap = require('..');
let data = [{
"name": "Name 1",
"about": "About 1",
"records": [
{
"date": "20180101",
"sum": 100,
"array": [
1, 2, 3
],
"count": 1
},
{
"date": "20180202",
"sum": [200, 300],
"count": 2
},
{
"array": [
3, 4, 5
],
"count": 3
},
],
}]
let mapping = {
"title": "name",
"description": "about",
"date": ["records.date", ""],
"sum": {
"getter": "records.sum",
"defaultValue": 0,
},
"array": {
"getter": "records.array",
"defaultValue": [],
"unwind": false,
},
"count": {
"getter": "records.count",
"defaultValue": 0,
"convert": function(val) {
return val * 3
},
},
"calculateMe": {
"calculate": function() {
return this.count + 1;
}
}
}
let result = JSONRemap(data, mapping);
console.log(JSON.stringify(result, null, 4));
Result:
[
{
"title": "Name 1",
"description": "About 1",
"calculateMe": 4,
"date": "20180101",
"sum": 100,
"array": [
1,
2,
3
],
"count": 3
},
{
"title": "Name 1",
"description": "About 1",
"calculateMe": 7,
"date": "20180202",
"array": [],
"count": 6,
"sum": 200
},
{
"title": "Name 1",
"description": "About 1",
"calculateMe": 7,
"date": "20180202",
"array": [],
"count": 6,
"sum": 300
},
{
"title": "Name 1",
"description": "About 1",
"calculateMe": 10,
"date": "",
"sum": 0,
"array": [
3,
4,
5
],
"count": 9
}
]
Documentation
JSONRemap parameters:
data
It can be null, primitive, an object or an array
mapping
It is a key-value object The key represents a key name in the output
The value can be:- String: a path for a key
- Array: First element is a key, second one is a default value
- Object:
License
MIT (see License)