JSON-Schema + fake data generators

Overview

JSON Schema Faker logo

Donate OpenCollective Build status NPM version Bower version Coverage Status

Gitter Dependency Status devDependency Status

Inline docs Typedoc Known Vulnerabilities

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

What's next?

Breaking-changes towards v0.5.x API:

  • deprecated — You will not longer be able to call jsf() and get a fully-dereferenced result. It will just generate given refs and inline ones, nothing else.
    • jsf.generate() is the sync-version, with partial dereferencing through given refs, etc.
    • jsf.resolve() is the async-version, with full dereferencing, given refs are also supported.
  • deprecated — TypeScript sources are not longer used, however d.ts definitions will be updated on time.

Usage info from README.md was moved to docs/, read more.

Contributors

We are more than happy to welcome new contributors, our project is still being developed, but we need more feedback!

Please see our contribution guide to learn how.

We are looking for your help!

We have a gitter room for this project, if you want to contribute, talk about specific issues from the library, or you need help on json-schema topics just reach out to us!

Please take a look at the technical documentation page.

If you think json-schema-faker is adding value on what you're doing please consider buying me a coffee.

Also, you can support the project via Open Collective.

Comments
  • Reference (still) not found

    Reference (still) not found

    Going back to #25. I can see, that [email protected] solves this issue. The problem is that [email protected] isn't included in json-schema-faker. Can we publish version 0.1.7 where, according to develop branch, the issue is solved? I think it's a minor fix and there's no need to wait for a bigger release. It's a bug afterall ;)

    opened by ducin 25
  • relative parameters / fake values re-used

    relative parameters / fake values re-used

    Hello,

    First of all, I find this tool amazing. Since I got to know JSON schema and faker I thought it would be great to use them together and here I see that such thing exists!

    The thing I need and I'm not sure whether it's supported is re-using fake data inside the same structure. Let's say, that I do use faker to generate a firstName and lastName and I want to reuse these values to generate email (see email: function (firstName, lastName, provider) as https://github.com/Marak/faker.js/blob/master/lib/internet.js).

    If I do this:

    {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "firstName": {
          "type": "string",
          "minLength": 2,
          "faker": "name.firstName"
        },
        "lastName": {
          "type": "string",
          "minLength": 2,
          "faker": "name.lastName"
        },
        "email": {
          "type": "string",
          "minLength": 2,
          "faker": "internet.email"
        }
      },
      "required": [
        "firstName",
        "lastName",
        "email"
      ]
    }
    

    I'll get:

    {
      firstName: "Andy",
      lastName: "Smith",
      email: "[email protected]"
    }
    

    and of course, I'd like to make it more like:

    {
      firstName: "Andy",
      lastName: "Smith",
      email: "[email protected]"
    }
    

    (provided first and last names are randomized). I know I can parametrize faker somehow, e.g.

    {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "firstName": {
          "type": "string",
          "minLength": 2,
          "faker": "name.firstName"
        },
        "lastName": {
          "type": "string",
          "minLength": 2,
          "faker": "name.lastName"
        },
        "email": {
          "type": "string",
          "minLength": 2,
          "faker": {
            "internet.email": [false, false, "gmail.com"]
          }
        }
      },
      "required": [
        "firstName",
        "lastName",
        "email"
      ]
    }
    

    it took me long time to figure it out... Anyway, can I re-use the firstName and lastName to produce email somehow? faker.js itself provides functions which accept those parameters, so the wrapper should not disable such feature.

    So is there any support for that? Are there plans to do so? Is there any discussion about that?

    major improvement discussion data generation working in progress 
    opened by ducin 22
  • Gracefully handle unrecognised types

    Gracefully handle unrecognised types

    Hello! First of all, thanks a lot for the great library.

    During our usage, we're dealing with some schemas which have an unrecognised type, such as customStructure and so on.

    Actually faker throws an exception, as you can see here.

    image

    It would be great if it could gracefully handle the situation like an empty string, or a default provided value, or skipping the field at all.

    Would you be interested in a PR fixing this thing? Which approach do you think would be the best one? Cheers!

    opened by XVincentX 19
  • Allow for faker.js locale to change the required AST when using Browserify

    Allow for faker.js locale to change the required AST when using Browserify

    faker.js has this nifty ability to require individual locales as documented here. The idea is that when using Browserify, you could use require('faker/locale/en_US') and only end up with the en/en_US locales being in the AST used by Browserify instead of having all locales in the AST.

    Right now, json-schema-faker does not allow the consumer to take advantage of this so when I use Browserify to bundle my project, I end up with an extra 751 files in my Browserify bundle. Here is how I came up with this number:

    // require('faker');
    browserify --list testing.js | wc -l
         862
    
    // require('faker/locale/en_US');
    browserify --list testing.js | wc -l
         111
    

    This has an impact on file size too, even with this one line module the file size is most than 3 times the size. All of this being said, is there a way to address this? I've got some ideas but before I spend the time, I wanted to make sure this was in fact a real issue and I wasn't missing something.

    Also, if you know of a Browserify recipe to handle this without altering json-schema-faker I'm all ears. I've looked into a few options but never found anything that worked.

    opened by whitlockjc 19
  • Cannot use 'in' operator to search for 'generate' in [Circular ~.properties .fields.items.oneOf.0.properties.values.items.oneOf.4.properties .values.oneOf.1.properties.values.items]

    Cannot use 'in' operator to search for 'generate' in [Circular ~.properties .fields.items.oneOf.0.properties.values.items.oneOf.4.properties .values.oneOf.1.properties.values.items]

    Please can anyone explain why I am getting this errors. I have a dereferenced schema which contains circular references, can't I be able to still generate random data for the schema with jsf.generate("schema.json") or it is not possible ?

    opened by Emdave10 18
  • alwaysFakeOptionals doesn't always fake

    alwaysFakeOptionals doesn't always fake

    If you are reporting a bug, please include the following:

    When using 0.5.0-rc16 it seems that alwaysFakeOptionals does not seem to work as i'd expect. Understand this is not yet released, so perhaps this is a known issue.

    With nested properties, these seem to only be occasionally generated, rather than always generated.

    You can try this out here... https://runkit.com/nizmox/5bc0228ecd3ca800122bc854

    question docs improvement working in progress 
    opened by s-taylor 18
  • [discussion] [help needed] freeze property values

    [discussion] [help needed] freeze property values

    Is there possible to freeze property value in item schema?

    // Fake Mongo item generator
    // type paramter is optional
    // If no type specified  - random value should be generated (0 or 1)
    // If type specified -  {'type': type} should be returned
    module.exports.mongoItem = function(type) {
        var itemSchema = { 
               type: {
                    type: 'integer',
                    enum: [0, 1] // type can be zero or one
                },
                required: ['type']
        }
       return jsf(itemSchema)
    
    question discussion 
    opened by hellboy81 18
  • Extending low-level dependencies

    Extending low-level dependencies

    There is one more thing I'd appreciate a lot: extending/parametrizing base libraries (e.g. faker). This is a must-have, when you want to customize it:

    • set the locale, which alters results in the end - faker provides internationalization feature: https://github.com/Marak/faker.js#localization.
    • extending the library with custom generators, that will make use of all existing features of the library (e.g. custom faker generators will reuse its locale definitions, which is unable using json-schema-faker format functions).

    Currently, jsf API looks like the following:

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

    I'm thinking of adding a jsf.customize(gen, fn) function, where gen is the generator (faker, chance, etc.) and fn is the callback like the following:

    function customizeFaker(faker) {
        faker.locale = "de"; // or whatever
        faker.customModule = {
            fn_1: function...
            fn_2: function...
            fn_n: function...
        };
        return faker;
    }
    

    Finally, the outside API would look like this:

    var jsf = require('json-schema-faker');
    var schema = ...
    jsf.customize('faker', function(faker){
        faker.locale = "de"; // or whatever
        faker.customModule = {
            fn_1: function...
            fn_2: function...
            fn_n: function...
        };
        return faker;
    });
    var sample = jsf(schema);
    

    Where customize is, of course, optional. This would encapsulate extending dependencies, which is impossible now, unfortunately. No matter who and how uses the json-schema-faker, he could add his own stuff. Currently, faker is just fetched from npm as-is and loaded using node.js require and you can do nothing with it.

    I can prepare a PR, but I need to know whether you're opened for such feature.

    opened by ducin 18
  • Update rollup to the latest version 🚀

    Update rollup to the latest version 🚀

    Version 0.60.1 of rollup was just published.

    Dependency rollup
    Current Version 0.57.1
    Type devDependency

    The version 0.60.1 is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.

    It might be worth looking into these changes and trying to get this project onto the latest version of rollup.

    If you have a solid test suite and good coverage, a passing build is a strong indicator that you can take advantage of these changes directly by merging the proposed change into your project. If the build fails or you don’t have such unconditional trust in your tests, this branch is a great starting point for you to work on the update.


    Commits

    The new version differs by 323 commits.

    • 264c867 0.60.1
    • d1b13f2 Merge branch 'large-var-count'
    • 647460f Merge branch 'ongenerate-fix'
    • fbde57e fix input validation after options hook
    • b0eda7c include fix for chunkId closure
    • 2b0b6c9 fix ongenerate signature regression
    • 662ee81 fix large variable count numbering
    • 12a6ae0 Fix style
    • 0bc6426 0.60.0
    • 916a759 Add release date to changelog
    • 6f973a4 Merge branch 'plugin-chunking'
    • a7058a6 fix inlineDynamicImports entry misrecognition bug
    • 649a046 tweak dir / file error message cases
    • b9f085a use native URL in tests if possible
    • 2a634c7 provide bundle on output property

    There are 250 commits in total.

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 16
  • JSON Faker generating values for non-required fields

    JSON Faker generating values for non-required fields

    With below schema the issue I got was faker generating values for non-required fields.

    1. the JSON Schema content that fails - http://json-schema-faker.js.org/#gist/1cbf360c8c0ae2d0a8247ac2b7980dd4/0.5.0-rc11
    2. the result you got { "title": "Ms", "firstName": "exercitation adipisicing culpa in" }
    3. the result you expected { "title": "Ms" }
    dependencies data generation working in progress needs investigation 
    opened by prateeksarda 16
  • Allow extending for arbitrary keywords

    Allow extending for arbitrary keywords

    Rather than opening a PR out of the blue, I thought I'd ask first:

    In our project, we use json-schema-faker to generate fake data according to a schema, however, because the data are used as React component props, we have some extensions in the schema itself for objects that are not strictly JSON. In order to extend the basic JSON schema, because extending with custom type is against the spec, we define custom keywords for custom things (e.g. { isFunction: true } instead of { type: 'function' }).

    While I know this is controversial and we probably shouldn't, the overwhelming majority of prop data is covered by JSON schema and the interoperability of it is extremely appealing.

    JSON schema faker currently doesn't support extending for custom keywords, but the support is "almost there". If external type detection looked at available extensions in container and the external type then delegated to any extension here (probably in order from last one defined to first one defined), it should be quite easy to do this. Unless I'm missing something.

    Is that something you'd be willing to accept as a PR?

    major improvement question discussion 
    opened by charypar 16
  • Unable to re-use fake values in OpenAPI schema

    Unable to re-use fake values in OpenAPI schema

    Using examples taken from issue and the great work done by @pateketrueke. I am unable to re-use generated data from other fields with an open api schema.

    1. The JSON Schema content that fails:
    openapi: 3.0.3
    components:
      schemas:
        UserType:
          type: object
          required:
            - emailAddress
          properties:
            firstName:
              type: string
              x-faker: name.firstName
            lastName:
              type: string
              x-faker: name.lastName
            fullName:
              type: string
              x-faker:
                name.fullName:
                  firstName: '#{firstName}'
                  lastName: '#{lastName}'
            emailAddress:
              type: string
              x-faker:
                internet.email:
                  - '#{firstName}'
                  - '#{lastName}'
                  - 'mycompany.com'
    
    1. Actual results:
    {
      "emailAddress": "[email protected]",
      "firstName": "Adaline",
      "lastName": "Barrows",
      "fullName": "#{firstName} #{lastName}"
    }
    
    1. Expected results:
    {
      "emailAddress": "[email protected]",
      "firstName": "Adaline",
      "lastName": "Barrows",
      "fullName": "Adaline Barrows"
    }
    
    1. Json-schema-faker settings:
    {
        locale: "en",
        minItems: 1,
        maxItems: 3,
        refDepthMax: 6,
        resolveJsonPath: true,
        alwaysFakeOptionals: true,
      }
    
    bug dependencies integration data generation 
    opened by ritchieanesco 1
  • dev sync: several fixes and updates

    dev sync: several fixes and updates

    Work in progress

    This PR would resolve several mistakes from bundles, from now now the published packages should be stable for ESM and for usage on Deno.

    It also includes other small contributions as well minor corrections, we want to include more fixes and small features before the next release!

    opened by pateketrueke 1
  • Invalid enums when using refs multiple times

    Invalid enums when using refs multiple times

    If you are reporting a bug, please include the following:

    The JSON Schema content that fails:

     {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "prop1": {
          "$ref": "#/definitions/EnumType",
          "description": "My prop1 description."
        },
        "prop2": {
          "$ref": "#/definitions/PropType",
          "description": "My prop2 description."
        },
        "prop3": {
          "$ref": "#/definitions/EnumType",
          "description": "My prop3 description."
        },
        "prop4": {
          "$ref": "#/definitions/PropType",
          "description": "My prop4 description."
        }
      },
      "required": [
        "prop1",
        "prop2",
        "prop3",
        "prop4"
      ],
      "additionalProperties": false,
      "definitions": {
        "EnumType": {
          "type": "string",
          "enum": [
            "Value1",
            "Value2"
          ],
          "description": "My enum description."
        },
        "PropType": {
          "type": "object",
          "properties": {
            "subProp": {
              "$ref": "#/definitions/EnumType",
              "description": "Sub Prop Description"
            }
          },
          "additionalProperties": false
        }
      }
    }
    

    The result you got:

    {
      "prop1": "Value2",
      "prop2": {
        "subProp": {
          "description": "Sub Prop Description"
        }
      },
      "prop3": "Value1",
      "prop4": {
        "subProp": {
          "description": "Sub Prop Description"
        }
      }
    }
    

    the result you expected:

    {
      "prop1": "Value2",
      "prop2": {
        "subProp": "Value1"
      },
      "prop3": "Value1",
      "prop4": {
        "subProp": "Value2"
      }
    }
    

    After some debugging it looks like the problem is in recursiveUtil.resolveSchema in the if (typeof sub.$ref === 'string') {...} block. In this case seenRefs[sub.$ref] gets below 0 and the code deletes the ref, but leaves the description.

    bug dependencies data generation needs investigation 
    opened by mk0sojo 2
  • Generates invalid output using `allOf: [{ contains }, { contains }]`

    Generates invalid output using `allOf: [{ contains }, { contains }]`

    Schema

    The following schema expresses that an array should contain at least ["A", "B"]:

    {
      "$schema": "http://json-schema.org/draft-07/schema",
      "type": "array",
      "items": { "type": "string" },
      "allOf": [
        { "contains": { "const": "A" } },
        { "contains": { "const": "B" } }
      ]
    }
    

    Expected Result

    Any that includes ["A", "B"], and optionally other strings:

    ["A", "B"]
    ["aute fugiat", "quis ut", "A", "B"]
    

    Actual Result

    Includes only the last item in the allOf.contains list ("B"):

    ["aute fugiat", "quis ut", "B"]
    

    can't share link since the feature appears to be broken (#726)

    bug dependencies data generation needs investigation 
    opened by alanorozco 1
  • FEATURE: fixed value for all properties

    FEATURE: fixed value for all properties

    Is there an option in the web generator page to use fixed value (like empty string"") for all properties? If not, it would be useful feature.

    opened by tokorhon 0
Owner
JSON Schema Faker
generating mock data!
JSON Schema Faker
a little DSL that outputs JSON schema

kontur a little DSL that outputs JSON schema instruction on validating request body in koa using ajv and kontur overview import { compile, bool, int,

null 78 Nov 8, 2020
Immutable persistent data collections for Javascript which increase efficiency and simplicity.

Immutable collections for JavaScript Immutable data cannot be changed once created, leading to much simpler application development, no defensive copy

Immutable.js 32.4k Dec 31, 2022
ClojureScript's persistent data structures and supporting API from the comfort of vanilla JavaScript

mori A simple bridge to ClojureScript's persistent data structures and supporting APIs for vanilla JavaScript. Pull requests welcome. Breaking changes

David Nolen 3.4k Dec 31, 2022
A complete, fully tested and documented data structure library written in pure JavaScript.

Buckets A JavaScript Data Structure Library Buckets is a complete, fully tested and documented data structure library written in pure JavaScript. Incl

Mauricio 1.2k Jan 4, 2023
Immutable persistent data collections for Javascript which increase efficiency and simplicity.

Immutable collections for JavaScript Immutable data cannot be changed once created, leading to much simpler application development, no defensive copy

Immutable.js 32.4k Jan 7, 2023
A simulation data generator

Mock.js Mock.js is a simulation data generator to help the front-end to develop and prototype separate from the back-end progress and reduce some mono

高云 墨智 18.7k Jan 4, 2023
mutate a copy of data without changing the original source

immutability-helper Mutate a copy of data without changing the original source Setup via NPM npm install immutability-helper --save This is a drop-in

Moshe Kolodny 5.1k Dec 29, 2022
🛠️construct-js is a library for creating byte level data structures.

??️construct-js is a library for creating byte level data structures.

Francis Stokes 1.3k Dec 14, 2022
The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-06/07/2019-09/2020-12 (draft-04 is supported

Ajv JSON schema validator 12k Jan 4, 2023
Generate deterministic fake values: The same input will always generate the same fake-output.

import { copycat } from '@snaplet/copycat' copycat.email('foo') // => '[email protected]' copycat.email('bar') // => 'Thurman.Schowalter668@

Snaplet 201 Dec 30, 2022
Convert JSON examples into JSON schema (supports Swagger 2, OpenAPI 3 and 3.1)

json-to-json-schema Convert JSON examples into JSON schema. Supports JSON Schema draft-05 used in Swagger 2.0 and OpenAPI 3.0 and new draft draft-2020

Redocly 9 Sep 15, 2022
JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Aykut Saraç 20.6k Jan 4, 2023
A repository to generate the fake json data from protobuf.

Mock Protobuf A command-line tool to mock protobuf! Table of Contents Install Usage Generate Mock Data Mock Server Mock Server Data Filter Include Fil

Jasonkay 9 Dec 7, 2022
A simple CLI to generate a starter schema for keystone-6 from a pre-existing prisma schema.

Prisma2Keystone A tool for converting prisma schema to keystone schema typescript This is a proof of concept. More work is needed Usage npx prisma2key

Brook Mezgebu 17 Dec 17, 2022
A util for getting data and metadata for all markdown files in a given dir. Useful for building static site generators

extract-md-data A util for getting data and metadata for all markdown files in a given dir. Useful for building static site generators. Usage Given th

Claire Froelich 2 Jan 6, 2022
Validate your Markdown frontmatter data against a JSON schema — remark-lint rule plugin

remark-lint-frontmatter-schema Validate Markdown frontmatter YAML against an associated JSON schema with this remark-lint rule plugin. Supports: Types

Julian Cataldo 20 Dec 10, 2022
✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo ?? https://jsfiddle.net/torrobin

Tor 7 Jul 31, 2022
Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.

http-fake-backend Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes. It actually can serve

Micromata GmbH 279 Dec 11, 2022
Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku

Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku. In this article, we will create and host a fake server that we can de

Israel David 0 Sep 5, 2022
simple PWA catalogue with vanilla javascript and json-server as a fake server

simple PWA catalogue with vanilla javascript and json-server as a fake server

bagher musavi 2 Mar 12, 2022