npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@df-legacy/json-schema-faker

v0.2.16

Published

JSON-Schema + fake data generators

Downloads

2

Readme

JSON Schema Faker logo

Build Status NPM version Bower version Coverage Status Inline docs

Dependency Status devDependency Status

Use JSON Schema along with fake generators to provide consistent fake data for your system.

Want to support jsf? We are looking for a free database hosting, please see the call for providers.

migrating to TypeScript

JSON Schema Faker migration to TypeScript

JSON-Schema-Faker is being migrated into TypeScript.

Table of contents

Online demo

See online demo.

Install

jsf is installable through 3 different channels:

npm

Install json-schema-faker with npm:

npm install json-schema-faker --save

bower

Install json-schema-faker with bower:

bower install json-schema-faker --save

cdnjs

JSON-Schema-faker is also available at cdnjs.com. This means you can just include the script file into your HTML:

# remember to update the version number!
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json-schema-faker/0.2.8/json-schema-faker.min.js"></script>

It will be fetched from the Content Delivery Network without installing any node.js package.

You can see an example JS fiddle based on jsf loaded from cdnjs.

Overview

JSON-Schema-faker (or jsf for short) combines two things:

  • The JSON-schema specification, that defines what is the allowed content of a JSON document
  • Fake data generators, that are used to generate basic or complex data, conforming to the schema. Following libraries come bundled with jsf:

Example usage

var jsf = require('json-schema-faker');

var schema = {
  type: 'object',
  properties: {
    user: {
      type: 'object',
      properties: {
        id: {
          $ref: '#/definitions/positiveInt'
        },
        name: {
          type: 'string',
          faker: 'name.findName'
        },
        email: {
          type: 'string',
          format: 'email',
          faker: 'internet.email'
        }
      },
      required: ['id', 'name', 'email']
    }
  },
  required: ['user'],
  definitions: {
    positiveInt: {
      type: 'integer',
      minimum: 0,
      exclusiveMinimum: true
    }
  }
};

var sample = jsf(schema);

console.log(sample.user.name);
// output: John Doe

Gist demos

Clone these gists and execute them locally (each gist has its own readme with instructions):

  • jsf console - minimal example of jsf working directly under command line
  • jsf grunt - example of jsf working under grunt.js

Supported keywords

Note that jsf supports (currently) the JSON-Schema specification draft-04 only. Below is the list of supported keywords:

  • $ref — Resolve internal references only, and/or external if provided.
  • required — All required properties are guaranteed, if not can be omitted.
  • pattern — Generate samples based on RegExp values.
  • format — Core formats only: date-time, email, hostname, ipv4, ipv6 and uri.
  • enum — Returns any of these enumerated values.
  • minLength/maxLength — Applies length constraints to string values.
  • minimum/maximum — Applies constraints to numeric values.
  • exclusiveMinimum/exclusiveMaximum — Adds exclusivity for numeric values.
  • multipleOf — Multiply constraints for numeric values.
  • items — Support for subschema and fixed item values.
  • minItems/maxItems — Adds length constraints for array items.
  • uniqueItems — Applies uniqueness constraints for array items.
  • additionalItems — Partially supported (?)
  • allOf/oneOf/anyOf — Subschema combinators.
  • properties — Object properties to be generated.
  • minProperties/maxProperties — Adds length constraints for object properties.
  • patternProperties — RegExp-based object properties.
  • additionalProperties — Partially supported (?)
  • dependencies — Not supported yet (?)
  • not — Not supported yet (?)

Using references

Inline references are fully supported (json-pointers) but external can't be resolved by jsf.

In order to achieve that you can use refaker and then use the resolved schemas:

var schema = {
  type: 'object',
  properties: {
    someValue: {
      $ref: 'otherSchema'
    }
  }
};

var refs = [
  {
    id: 'otherSchema',
    type: 'string'
  }
];

var sample = jsf(schema, refs);

console.log(sample.someValue);
// output: voluptatem

Faking values

jsf has built-in generators for core-formats, Faker.js and Chance.js are also supported.

You can use faker or chance properties but they are optional:

{
  "type": "string",
  "faker": "internet.email"
}

The above schema will invoke:

require('faker').internet.email();

Another example is passing arguments to the generator:

{
  "type": "string",
  "chance": {
    "email": {
      "domain": "fake.com"
    }
  }
}

And will invoke:

var Chance = require('chance'),
  chance = new Chance();

chance.email({ "domain": "fake.com" });

If you pass an array, they will be used as raw arguments.

Note that both generators has higher precedence than format.

You can also use standard JSON Schema keywords, e.g. pattern:

{
  "type": "string",
  "pattern": "yes|no|maybe|i don't know"
}

BREAKING CHANGES

Since 0.3.0 the faker and chance dependencies aren't shipped by default, in order to use both generators you MUST install them with npm install faker chance --save.

Custom formats

Additionally, you can add custom generators for those:

jsf.formats('semver', function(gen, schema) {
  return gen.randexp('^\\d\\.\\d\\.\\d{1,2}$');
});

Now that format can be generated:

{
  "type": "string",
  "format": "semver"
}

Usage:

  • formats() — Return all registered formats (custom only)
  • formats(obj) — Register formats by key/value → name/callback
  • formats(name) — Returns that format generator (undefined if not exists)
  • formats(name, callback) — Register a custom format by name/callback

Callback:

  • gen (object) — Built in generators
    • faker (object) — Faker.js instance
    • chance (object) — Chance.js instance
    • randexp (function) — Randexp generator
  • schema (object) — The schema for input

Note that custom generators has lower precedence than core ones.

Extending dependencies

You may extend Faker.js:

var jsf = require('json-schema-faker');

jsf.extend('faker', function(faker){
  faker.locale = "de"; // or any other language
  faker.custom = {
    statement: function(length) {
      return faker.name.firstName() + " has " + faker.finance.amount() + " on " + faker.finance.account(length) + ".";
    }
  };
  return faker;
});

var schema = {
  "type": "string",
  "faker": {
    "custom.statement": [19]
  }
}

var sample = jsf(schema);

or if you want to use faker's individual localization packages, simply do the following:

jsf.extend('faker', function() {
  // just ignore the passed faker instance
  var faker = require('faker/locale/de');
  // do other stuff
  return faker;
});

You can also extend Chance.js, using built-in chance.mixin function:

var jsf = require('json-schema-faker');

jsf.extend('chance', function(chance){
  chance.mixin({
    'user': function() {
      return {
        first: chance.first(),
        last: chance.last(),
        email: chance.email()
      };
    }
  });

  return chance;
});

var schema = {
  "type": "string",
  "chance": "user"
}

var sample = jsf(schema);

The first parameter of extend function is the generator name (faker or chance). The second one is the function that accepts the dependency library; the function alters the library and returns it.

Inferred Types

JSON Schema does not require you to provide the type property for your JSON Schema documents and document fragments.

But since jsf uses the type property to create the proper fake data, we attempt to infer the type whenever it is not provided. We do this based on the JSON Schema validation properties you use.

Now this means that if you do not use any of the JSON Schema validation properties, jsf will not be able to infer the type for you and you will need to explicitly set your type manually.)

Below is the list of JSON Schema validation properties and the inferred type based on the property:

array

  • additionalItems
  • items
  • maxItems
  • minItems
  • uniqueItems

integer (Number uses the same properties so if you need number, set your type explicitly)

  • exclusiveMaximum
  • exclusiveMinimum
  • maximum
  • minimum
  • multipleOf

object

  • additionalProperties
  • dependencies
  • maxProperties
  • minProperties
  • patternProperties
  • properties
  • required

string

  • maxLength
  • minLength
  • pattern

Bundling

JSON-Schema-faker might be used in Node.js as well as in the browser. In order to execute jsf in a browser, you should include the distribution file from dist directory. Each new version of jsf is bundled using browserify and stored by the library maintainers. The bundle includes full versions of all dependencies.

However, you may want to bundle a smaller package of jsf, because:

  • you want to reduce the bundle file size
  • you don't need all languages from faker.js
  • you wish to use chance.js only and get rid of other dependencies
  • or for any other reason... In that case you may bundle the distribution yourself manually. It's easily achievable: just modify the lib/util/container.js file and either remove o rmodify the require calls (they're directly used by browserify to include dependencies). Automation of this feature is expected in near future.

Automation

Grunt plugin

Use grunt-jsonschema-faker to automate running json-schema-faker against your JSON schemas.

Resources

Motivation

There were some existing projects or services trying to achieve similar goals as jsf:

  • http://www.json-generator.com/
  • https://github.com/unindented/fake-json
  • https://github.com/jonahkagan/schematic-ipsum
  • https://www.npmjs.org/package/json-schema-mock
  • https://github.com/thaume/json-schema-processor
  • https://github.com/andreineculau/json-schema-random
  • https://github.com/murgatroid99/json-schema-random-instance
  • https://github.com/tomarad/JSON-Schema-Instantiator

but they were either incomplete, outdated, broken or non-standard. That's why jsf was created.

Contribution

Any contribution is well received, please see contribution guide.

Bitdeli Badge