Home

Awesome

json-creator

Generate JSON data from a JSON template. Thanks to ES6 Template Literals, we dynamicly evaluate the string parts using the notation ${}.

This is a useful library for dummy data generating or generally data processing.

Usage

npm install json-creator
import jsonCreator from 'json-creator';
// or using CommonJS
// const jsonCreator = require('json-creator').default;

const template = [
    {
        '3..5': {
            name: '${FAKE("{{commerce.productName}}")} ${RANDINT(1000,10000)}'
        }
    }
];
const [result, err] = jsonCreator(template);
// result:
// [
//   {
//     'name': 'Handmade Metal Salad 2102'
//   },
//   {
//     'name': 'Small Metal Mouse 6396'
//   },
//   {
//     'name': 'Rustic Granite Shirt 5762'
//   },
//   {
//     'name': 'Ergonomic Soft Chicken 5489'
//   }
// ]

API

The json-creator interface was some kind of inspired by json-generator (by Vazha Omanashvili), but simpler to learn and use, IMO.

function jsonCreator(
    template = null,
    dataContext = {},
    methodContext = utilFunctions,
    dataNamespace = '_',
    methodNamespace = ''
)

The template is a json-like any-type template data.

// generate data with dataContext
jsonCreator(
    {
        name: ['${_.firstName}', '${_.lastName}'],
        age: '${RANDINT(_.from, _.to)}'
    },
    {
        firstName: 'Charlie',
        lastName: 'Green',
        from: 10,
        to: 50
    }
);
// [ { name: [ 'Charlie', 'Green' ], age: 32 }, [] ]

This library uses JavaScript ES2015 template literals evaluation behind the scenes, but there are 2 key differences in our dynamic evaluation.

Just like the example above, even though the age in the template is defined as a string, the evaluation result will keep the type (age: 32 is evaluated into number, not a string "32"). But '{${1} ${2}}' will be evaluated into '1 2', since a number type cannot hold both values and a space between them.

Also, there are some default utilFunctions that is convenient to use. You can import and use them directly, or add your own util functions. e.g.

import jsonCreator, { utilFunctions } from 'json-creator';
import moment from 'moment';
// or using CommonJS
// const jsonCreator = require('json-creator').default;
// const { utilFunctions } = require('json-creator');
// const momnet = require('moment');

utilFunctions.RANGE(2, 8, 2);
// [ 2, 4, 6 ]

jsonCreator(
    { time: '${MOMENT().format("YYYY/MM/DD")}', description: '${_.str}' },
    { str: 'today' },
    Object.assign({ MOMENT: moment }, utilFunctions)
);
// [ { time: '2019/07/09', description: 'today' }, [] ]

Built-in utilFunctions

Here is a brief list of the currently supported built-in utilFunctions.

CLI

You can install the pacakge globally and use the commandline tool for convinience.

npm install -g json-creator

json-creator command recieves the template (in JSON5 format) from stdin. e.g.

$ echo '[{"3...5": "${RANGE(_.a, _.b)}"}]' | json-creator -d '{a:10, b:15}'

[[10,11,12,13,14],[10,11,12,13,14],[10,11,12,13,14],[10,11,12,13,14],[10,11,12,13,14]]

Output with 4-space indent JSON:

$ echo '[{"3..5": "${FAKE(`{{hacker.phrase}}`)}"}]' | json-creator -i 4

[
    'If we compress the bandwidth, we can get to the PNG sensor through the optical IB program!',
    "I'll navigate the bluetooth CSS capacitor, that should card the RSS program!",
    "You can't transmit the program without overriding the solid state JBOD transmitter!",
    'The PNG bus is down, compress the primary monitor so we can transmit the HDD protocol!'
]

The help message shows the command options.

$ json-creator -h
Usage: cli [options]

Options:
  -V, --version                       output the version number
  -d, --data-context [object]         data context
  -m, --method-context [object]       method context
  -n, --data-namespace [namespace]    data namespace, default to "_"
  -g, --method-namespace [namespace]  data namespace, default to global context
  -i, --json-indent [indent]          output json indent number (default: 0)
  -l, --list                          output available util functions
  -h, --help                          output usage information