@programmerraj/jsonv
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

Test License TS-Standard - Typescript Standard Style Guide

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' }

Contributing

JavaScript Style Guide

Package Sidebar

Install

npm i @programmerraj/jsonv

Weekly Downloads

1

Version

2.1.0

License

MIT

Unpacked Size

11.9 kB

Total Files

7

Last publish

Collaborators

  • programmerraj