jsonfork
JSON folk-transforming tool
Install
npm install --save jsonfork
Example
Define the transformer
:
var jsonfork = require('jsonfork');
var transformer = new jsonfork({
source: {
name: 'Billing',
schema: {
"type": "object",
"properties": {
"title": { "type": "string" },
"fromTime": { "type": "string" },
"toTime": { "type": "string" },
"customerId": { "type": "string" },
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"label": { "type": "string" },
"price": { "type": "number" },
"amount": { "type": "number" }
},
"required": ["label", "price", "amount"]
}
}
}
}
},
targets: [{
name: 'Details',
transform: function(data, bill_opts) {
return {
title: data.title + ' [' + data.customerId + ']',
customerId: data.customerId,
items: data.items
}
},
eventName: 'BillingDetails'
},{
name: 'Summary',
transform: function(data, bill_opts) {
var summary = data.items.reduce(function(sum, item) {
sum.count += item.amount;
sum.total += item.amount * item.price;
return sum;
}, { count: 0, total: 0 });
if (bill_opts.tax > 0) {
summary.total *= (1 + bill_opts.tax);
}
return {
title: data.title + ' [' + data.customerId + ']',
customerId: data.customerId,
count: summary.count,
total: summary.total
}
},
schema: {}
}]
});
transformer.on('BillingDetails', function(result) {
console.log('Details (from event): %s', JSON.stringify(result));
});
transformer.on('Summary', function(result) {
console.log('Summary (from event): %s', JSON.stringify(result));
});
Use transformer
to transform json data:
var bill_opts = { tax: 0.1 };
var result = transformer.transform({
title: 'JsonFork Billing',
customerId: 'hello.com',
items: [
{ label: 'Item#1', price: 15, amount: 2 },
{ label: 'Item#2', price: 17, amount: 3 }
]
}, bill_opts);
console.log('Result: %s', JSON.stringify(result, null, 2));