1.0.3 • Published 7 years ago
json-programable-template v1.0.3
json-programable-template
Install
$ npm i json-programable-template --save
Example
Here is a basic example
const helloWorld = {
"rules":{
hello:"const@hello",
world:"const@world",
}
};
const model = new JSONNormal().parseJson(helloWorld,null);
output: { hello: 'hello', world: 'world' }
let us move a bit deeper
const sum = {
"rules":{
sum:"const@1 => sum@5,6",
sumTwo:"const@1 => sum@10,11",
}
};
const model = new JSONNormal().parseJson(sum);
output: { sum: 11, sumTwo: 21 }
You can use key word '~' to get previous value
const sum = {
"rules":{
sum:"const@1 => sum@~,~,10",
sumTwo:"const@1 => sum@10,11",
}
};
const model = new JSONNormal().parseJson(sum);
output: { sum: 12, sumTwo: 21 }
You also can define and use you own function here as well
const moment = require('moment');
let func = {
time(value) {
if (
"now" === arguments[0]
){
return moment().format(arguments[1]);
}
if (
arguments.length > 2
){
return moment(arguments[0], arguments[1]).format(arguments[2]);
} else {
return moment(arguments[0]).format(arguments[1]);
}
},
};
const sum = {
"rules":{
currentTime:"time@now",
parseTime: "const@20181021 => time@~,YYYY-MM-DD,YYYY-MM-DD HH:mm:ss"
}
};
const model = new JSONNormal().parseJson(sum,func);
output:
{
currentTime: '2018-10-22T15:58:21+08:00',
parseTime: '2018-10-21 00:00:00'
}
however the arguments you passed in the function should follow the rules:
function(argOne, argTwo, argThree, custom variable);
The last argument have to leave the space to the custom variable.
Validation:
You can add validation in the template
In this example, because 123 is num, the template would display an output
let func = {
isNum(value){
return !isNaN(Number(value));
}
};
const sum = {
"rules":{
hello:"const@hello",
world:"const@world",
},
"validator":[
"const@123 => isNum@~",
]
};
output: { hello: 'hello', world: 'world' }
If the validation is failed, return null;
const sum = {
"rules":{
hello:"const@hello",
world:"const@world",
},
"validator":[
"const@123 => isNum@~",
"const@aa => isNum@~"
]
};
output: null
const model = new JSONNormal().parseJson(sum,func);
Questions & Suggestions
Please open an issue here.