json4json
👻 Json template for json.
Inspired by st.js
Playground
https://baffinlee.github.io/json4json/
Install
npm install json4json# or yarn # yarn add json4json
Usage
general
need Node.js >= 8
const transform = const template = '{{val}}'const data = val: 1const result = // 1
in web browser
need
new Function
support
full example
const transform = const template = simpleValue: '{{value}}' optionalValue: '{{#? optionalValue}}' iteration: object: '{{#each object}}': '{{$key}}' '{{$item.example}}' '{{keyInItem}}' array: '{{#each array}}': '{{$key}}' '{{$item.example}}' '{{keyInItem}}' conditions: '{{#if Math.round(num) === 10}}': 'if' '{{#elseif $root.num > 10}}': 'elseif' '{{#else}}': 'else' mergeObjects: '{{#merge}}': a: 1 b: 1 c: 1 b: 2 c: 2 '{{#if false}}': {} '{{#else}}': c: 3 concatArrays: '{{#concat}}': 1 2 3 '{{#each array}}': '{{$key + 4}}' 5 localVariables: '{{#let}}': var1: 'val5' var2: 'val6' '{{var1}}' '{{var2}}' const data = value: 'any value' optionalValue: false object: key1: example: 'val1' keyInItem: 'val2' array: example: 'val3' keyInItem: 'val4' num: 106 const result = /*result = { simpleValue: 'any value', // optionalValue droped iteration: { object: [ ['key1', 'val1', 'val2'] ], array: [ [0, 'val1', 'val2'] ] }, conditions: 'elseif', mergeObjects: {a: 1, b: 2, c: 3}, concatArrays: [1, 2, 3, 4, 5], localVariables: ['val5', 'val6']}*/
api
transform(template, data, options)
params:
-
template
{object | array | string} -
data
{object} optional -
options
{object} optional -
options.onError
{function} optional, error handlerparams:
message
{string} error messagepath
{array} template path where error occurs, like['root', 'arr', 1, '{{#if val}}', 'key']
context
{object} data context at there, like{$root: {}, val: '', $item: {}, $key: ''}
return:
- {any}
Syntax
$root
in the bottom of context represents the root data (object)
value
{{var}}
=> any
example:
const data = key: 1 // '1' // {val: '1'} // {1: '1'}
optional value
{{#? var}}
=> any | empty | null
example:
const data = key: 0 // null // {} // {} // []
conditional statement
{ '{{#if condition}}': '', '{{#if condition}}': '', '{{#else}}': '' }
=> any
example:
const data = num: 10 // 1
iteration
{ '{{#each data}}': '' }
=> array
$key
and$item
will push to context, if$item
is a plain object, all it's key will push to context
example:
const arr = itemKey: 'itemVal' const obj = key: itemKey: 'itemVal' // [ { key: 0, item: true, data: 'itemVal' } ] // [ { key: 'key', item: true, data: 'itemVal' } ]
merge objects
like
Object.assign
{ '{{#merge}}': [ { a: 1 }, { b: 2 } ] }
=> object
example:
const data = val: 3 // { a: 1, b: 2, c: 3 }
concat arrays and items
{ '{{#concat}}': [ 1, 2, [ 3, 4], 5 ] }
=> array
example:
const data = val: 3 // [ 1, 2, 3, 4 ]
local variables
{ '{{#let}}': [ { localVar: 1 }, '{{localVar}}' ] }
=> any
example:
const data = globalVar: 3 // 4 // 3