@programmerraj/jsonv
v2.1.0
Published
Json with variables.
Downloads
3
Maintainers
Readme
jsonv
Json with variables.
Why
When editing json, it can be very annoying to change a certain value that's used in multiple places.
{
"points": [
{
"x": 53,
"y": 0
},
{
"x": 53,
"y": 10
},
{
"x": 53,
"y": 20
}
]
}
In the example above, all of the objects have the same x
value. If we want to tweak the number for x
, it will be tedious to change it for every single object.
The solution: jsonv.
{
"$jsonv": {
"x": 53
},
"points": [
{
"x": { "$jsonv": "x" },
"y": 0
},
{
"x": { "$jsonv": "x" },
"y": 10
},
{
"x": { "$jsonv": "x" },
"y": 20
}
]
}
Now all you have to change to change x
is the vars at the top.
Syntax
Declaring Vars
You can declare variables in any object by adding a $jsonv
key. Its value should be an object where the keys are names of variables and values are their corresponding values.
{
"$jsonv": {
"myVar": 24,
"anotherVar": ["a", "json", "value"]
}
}
Referencing Vars
When $jsonv
is a string, it is a reference to a variable.
{
"$jsonv": "nameOfVar"
}
Nested Vars
Variables in nested objects are similar to JavaScript const
variables.
{
"$jsonv": {
"a": "hi"
},
"a": { "$jsonv": "a" },
"obj1": {
"$jsonv": {
"a": "hello"
},
"a": {
"$jsonv": "a"
}
},
"obj2": {
"a": {
"$jsonv": "a"
}
}
}
This will compile into
{
"a": "hi",
"obj1": {
"a": "hello"
},
"obj2": {
"a": "hi
}
}
Install
@programmerraj/transform-json
is a peerDependency
.
npm i @programmerraj/transform-json @programmerraj/jsonv
Usage
More information about transform-json
ES
import jsonv from 'jsonv'
CommonJS
const jsonv = require('jsonv').default
Transforming Json
transform({
$jsonv: {
a: 'hi'
},
a: { $jsonv: 'a' },
b: { $jsonv: 'b' }
}, [jsonv(parser({
b: 'Given Var'
}))])
// Returns { a: 'hi', b: 'Given Var' }