Giter VIP home page Giter VIP logo

json-schema-faker's Introduction

JSON Schema Faker logo

Donate OpenCollective Build status NPM 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

Artwork by Ajay Karat

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.

json-schema-faker's People

Contributors

0xbadbac0n avatar adrienv1520 avatar arjanvanderleden avatar arnabguptadev avatar benjamin-mogensen avatar dependabot[bot] avatar ducin avatar ehmicky avatar greenkeeper[bot] avatar greenkeeperio-bot avatar holvi-sebastian avatar hxtree avatar jonau avatar jounqin avatar liangskyli avatar mayacoda avatar michaelmior avatar michamos avatar ndbroadbent avatar oktapodia avatar pateketrueke avatar peterdavehello avatar peterwald avatar presidento avatar rachidlamouri avatar rfoel avatar skipjack avatar whitlockjc avatar xvincentx avatar zepatrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-schema-faker's Issues

[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)

Reference not found

I was encountering a problem with the example snippet from the readme. I just copied the code as-is:

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,
      minimumExclusive: true
    }
  }
};

var sample = jsf(schema);

console.log(sample.user.name);

saved it in index.js (or whatever file), ran npm install json-schema-faker and ran this node code: node index.js. And I got an error:

c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\lib\index.js:23
      throw e;
            ^
Error: Reference not found: http://json-schema.org/schema#/definitions/positiveInt
    at module.exports (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\find-reference.js:38:11)
    at clone (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:15:17)
    at clone (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:34:19)
    at clone (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:34:19)
    at clone (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:34:19)
    at clone (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:34:19)
    at Object.module.exports [as resolveSchema] (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\util\resolve-schema.js:55:10)
    at $ref (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\node_modules\deref\lib\index.js:48:14)
    at generate (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\node_modules\json-schema-faker\lib\index.js:18:21)

    at Object.<anonymous> (c:\Users\tomasz.ducin\Tests\jsf-ref-broken\index.js:35:14)

To run any jsf code, I had to cut & paste the reference to the schema inside (removing definitions key). Then it started working. So, more or less, it seems that the main example in the docs might not work as expected. Are there any tests for that? Or maybe it's platform-dependent - I'm working on windows, unfortunately.

Generate ONLY required fields?

Is it possible, when generating JSON, to limit it to only the required fields? Right now it mandates required fields and randomizes the others.

We're trying to use this to generate auto-updating documentation, and including non-required properties could confuse things.

Make faker dependency optional

In my fakes for unit tests only chance library is used to generate both fake values (strings, numbers etc) and object from JSON scheme.

var jsf     = require('json-schema-faker'),
    chance  = require('chance').Chance() // And no faker dependency

Why faker dependency is still required by json-schema-faker?

`module.js:340
    throw err;
          ^
Error: Cannot find module 'faker'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (.../node_modules/json-schema-faker/lib/util/container.js:8:10)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (.../node_modules/json-schema-faker/lib/index.js:3:17)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (.../test/unit/fakes/index.js:3:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (.../test/unit/addon/module.private.spec.js:7:21)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at .../node_modules/mocha/lib/mocha.js:216:27
    at Array.forEach (native)
    at Mocha.loadFiles (.../node_modules/mocha/lib/mocha.js:213:14)
    at Mocha.run (.../node_modules/mocha/lib/mocha.js:453:10)
    at Object.<anonymous> (.../node_modules/mocha/bin/_mocha:401:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

[critical] build tests fail - references

Today I made one commit - changed pateketrueke into json-schema-faker in all markdown/readme links (7b058b4). This caused the tests to fail...

The bug had to be somewhere there before - or the dependencies started to work in different way, dunno yet. Anyway, there are two similar fails

(1) I made that commit locally and my travis failed: https://travis-ci.org/ducin/json-schema-faker/builds/78351520

Failures:
  1) schema references (core/references.json) should handle internal $refs
   Message:
     schema references (Value 24 is not a multiple of 5)

(2) I moved the commit to official repo (travis hasn't failed yet and I ddin't expect that to!): https://travis-ci.org/json-schema-faker/json-schema-faker/builds/78351806

Failures:
  1) schema references (core/references.json) should handle internal $refs
   Message:
     schema references (Value 76 is not a multiple of 5)

it's the same test, but the generated value seems to be different in both cases. It seems like multipleOf is not interpreted correctly, somehow.

Dunno if that's relevant, but I can see that deref repo is failing as well: https://travis-ci.org/json-schema-faker/deref

@pateketrueke do you know something about what might have caused this multipleOf bug?

travis build failing

This is very suspicious. Until now everything was working fine. Today I bumped faker.js 2.1.3 -> 2.1.4 and suddenly, travis build crashed. So I reverted the commit (which retriggered the travis build) and it failed again. I got no idea on what's going on, but in https://travis-ci.org/pateketrueke/json-schema-faker/builds/65619706 I can see that there are some methods missing:

  • TypeError: Object [object Object] has no method 'toHaveSchema'
  • TypeError: Object [object Object] has no method 'toHaveType'

@pateketrueke do you have any idea what can this be connected with?

Improperly handling 'allOf' block

I've got an issue that stems from a schema something like the one below. I can also reproduce on your web-based generator here.

{
    "allOf": [{
        "required": ["order"],
        "properties": {
            "order": {
                "type": "string"
            }
        }
    }, {
        "required": ["id"],
        "properties": {
            "id": {
                "type": "number"
            }
        }
    }]
}

If I plug in the proceeding schema, all but the last object listed in the allOf array is ignored. The output of above is as follows:

{
  "id": 75693268
}

When it should also include the "order" property outlined in the first object. Any thoughts?

select jsf version on demo page

Jsf has several versions published so far. Let's extend gh-pages and browserify all versions and let user choose (a GUI dropdown) online jsf version to generate data

online demo improvements

@pateketrueke in #14 you wrote:

  1. Semantic-UI/UI-Kit
  2. CodeMirror for editing JSON
  3. Use localStorage for storing schemas/refs
  4. A bulk functionality to download all compiled schemas

Can you describe above points more precisely? I think I understand what you mean in point 3.

[question] [discussion] [help needed] Generating json object with random key

How can I generate object with random key that has following schema:

{
            type: 'string',
            chance: {
                hash: {
                    casing: 'upper',
                    length: 32
                }
            }
}

Key should be generated on the basis of previous schema (random upper-cased string with length 32)

{
   "110B949E3BF0FE7C0DC15A17F04FA53E": { // Fake object is generating based on another schema 
      ... // Some fields
    }
}

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 ;)

allOf doesn't work properly

Hey there,
First, thanks a lot for this super useful lib. :)

I have a problem with allOf. When used, it seems to only include the last schema passed. Here is an example :

var testSchema = {
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "#/definitions/address" },
    "shipping_address": {
      "allOf": [
        { "$ref": "#/definitions/address" },
        { "properties":
          { "type": { "enum": [ "residential", "business" ] } },
          "required": ["type"]
        }
      ]
    }
  }
};

jsf(testSchema);

The resulting JSON looks like this :

{
  "shipping_address": {
    "type": "business"
  },
  "billing_address": {
    "street_address": "dolorum minima asperiores quas",
    "city": "quae ut explicabo",
    "state": "aspernatur ea est"
  }
}

(example taken from http://spacetelescope.github.io/understanding-json-schema/structuring.html)

I'm not sure the problem actually comes from json-schema-faker. Most likely from a dependency. I'll investigate further when I have some time.

reusing compiled schemas

It would be faster for other tools, relying on jsf, to re-use initially compiled schema. So far, there is jsf(schema) used to generate an object, which means that the schema needs to be read each time for each object. Unless I don't know there is a better solition. Is there :)?

E.g. in my grunt jsf plugin: https://github.com/tkoomzaaskz/grunt-jsonschema-faker/blob/master/tasks/jsonschema_faker.js#L49-L51 I need to re-compile the schema in a loop. What I'm thinking of is to provide a way to compile the schema once and enable users to massively generate the schema.

I do use it to generate arrays, that's true. And there are arrays in json schema, that's also true :-). However, when I hold json schemas, I would like to have a single object schema, which I'll use to validate. And I'd prefer to be able to generate a whole collection of test data (which means not including the array in the schema).

Awaiting your feedback, before I move on, Alvaro 🍻

Custom generators

We're using z-schema to register custom formats, for example semver:

ZSchema.registerFormat('semver', function(str) {                                                                                                                          
  return semver().test(str);                                                                                                                                              
});                                                                                                                                                                       

Schema:

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

Since Faker doesn't have a semver generator, is there a way to pass in a custom one?

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?

Error: Unknown primitive "[object Object]" at traverse

Error: Unknown primitive "[object Object]" at traverse

Any idea what would cause this error?

Also, key paths would be super handy in debugging. For example, this coffeescript code produces key paths like "foo.bar.baz" from an object:

isObject = (obj) -> Object.prototype.toString.call(obj) is '[object Object]'
allProperties = (object, path=[]) ->
  props = []
  for key, val of object
    here = path.concat([key])
    props.push here.join(".")
    if isObject val
      props.push allProperties(val, here)...
  props

Error messages could thus be "Error in foo.bar.baz: ...." so it was clear what was breaking.

stable releases

Hi @pateketrueke and @whitlockjc,

Recently we've had a situation where the master branch travis status turned into failing with no code changes. There were only docs changes. Actually, this one is still not fixed. I've got no idea on how did this happen...

What I would like to achieve is to make master branch stable 100%, both npm and github. And to achieve that, we need passing travis builds. There is a guideline stating that all changes for upcoming releases shall go to develop branch. And somewhere, somehow, we've made a mistake...

Do you know what was the problem? Do you have any suggestions on what can we improve to avoid such situation in future? The only thing I can think of is that upgrading dependencies should be done in develop branch as well and maybe this caused the instability.

re-using multiple subschemas between schema files

I've got a very big schema (thousands of files), which I have finally split into multiple files (according to docs). There is one "master" schema and over a dozen of chunk-schemas. I want to reuse simple structures between all of them, such as:

  "tinyId": {
    "type": "integer",
    "minimum": 1,
    "maximum": 100
  }

When I had one big file, I used to keep everything in definitions, just like below:

{
  //...
  "definitions": {
    "random": {
      "tinyId": {
        "type": "integer",
        "minimum": 1,
        "maximum": 100
      },
      "smallId": {
        "type": "integer",
        "minimum": 1000,
        "maximum": 1000000
      },
      "id": {
        "type": "integer",
        "minimum": 1000000,
        "maximum": 1000000000
      },
  //...

but after splitting the files, it breaks (definitions aren't resolved correctly.

What am I doing wrong? Does jsf support sharing subschemas between multiple files? Can I make one file that would hold many re-usable schemas?

Context

Hello there, how can I assign contexts to my schemas? I would like to do something like this:

{
  id: 'hello-world',
  properties: {
    id: {
      $ref: '#/context/query/id'
    }
  },
  context: {
    query: {
      id: 80
    }
  }
}

[critical] numbers error

While looking at #68 I've found another bug. In the last travis build I foud there is another test failing:

  1) using numbers (core/issues/numbers.json) should generate negative values
   Message:
     using numbers (Value -11 is less than minimum -10)

so I took a look at the schema, wrapped it in a big array and put it into our demo page. The schema is:

{
    "type": "array",
    "items": {
        "type": "integer",
        "minimum": -10,
        "maximum": -5
    },
    "maxItems": 150,
    "minItems": 100
}

and an example result is:

[
  -7,
  -9,
  -7,
  -7,
  -8,
  -7,
  -7,
  -11,
  -8,
  -9,
  -6,
// truncated

As you can see, there is -11.And there is obviously no deref/refaker. So there has to be some bug in the number properties logic. I'll take a look at it.

Infer type issues

This schema is failing:

{
  "id": "matches",
  "type": "object",
  "required": ["items"],
  "properties": {
    "items": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "minItems": 1,
      "maxItems": 10
    }
  }
}

Expected:

{
    "items": [
        "accusamus eveniet veritatis dolores impedit", 
        "voluptatem eaque", 
        "hic perspiciatis sapiente", 
        "sed culpa eveniet", 
        "nihil a", 
        "quisquam vitae praesentium", 
        "fugit voluptas inventore sunt ut", 
        "sit accusamus omnis ducimus expedita"
    ]
}

Actual result:

[
    [
        "odit et hic", 
        "possimus ex nobis amet", 
        "est unde sed", 
        "cum sequi ea itaque velit", 
        "consequuntur quia", 
        "quidem quasi nam", 
        "voluptas possimus iusto dolore", 
        "est ea quia", 
        "ea quisquam omnis mollitia"
    ], 
    [
        "quia incidunt", 
        "nesciunt", 
        "ut", 
        "at repellendus commodi", 
        "id quaerat laudantium quidem", 
        "modi expedita", 
        "dignissimos asperiores voluptatem nihil consequatur"
    ]
]

If I change the property name to anything else (but infer keywords) works properly.

if the inferred type is an object having a type keyword should stop inferring?

cc: @whitlockjc

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.

generating array of enums

I'm trying to provide an example faker schema that would generate an array of enumerations. That is, I specify possible values of the enum and give minimum number of items in the array. I've tried:

{
  "type": "array",
  "minItems": "15",
  "items": [
    {
      "enum": [ "red", "green", "blue" ]
    }
  ]
}

but it doesn't generate what I expect. It creates things like the following:

[
  "green"
]

or

[
  "red"
]

or

[
  "green"
]

etc. And I expect:

[
  "green",
  "red",
  "green",
  "blue",
  "red",
  "green",
  "blue",
  "red",
  ...
]

Does json-schema-faker not support that feature or am I doing something wrong?

extending specs allowing to extend dependencies

I've seen that the specs are defined through json files, containing test-definitions, e.g.

      {
        "description": "should handle format (faker)",
        "schema": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "faker": "name.findName"
            },
            "email": {
              "type": "string",
              "faker": "internet.email"
            }
          },
          "required": ["name", "email"]
        },
        "valid": true
      },

It is very self-descriptive, but it inherits flaws of JSON: it cannot include functions. And if I want to add a function to extend faker/chance (see #12), I have to do something else...

I think these are the lines that cause problems: https://github.com/pateketrueke/json-schema-faker/blob/master/spec/main-spec.coffee#L41-L45. According to #12, I should be able to run:

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);

so there should be something like:

          sample = try
            jsfaker(schema, refs)
            jsfaker.customize(function) <- ADDED
          catch e
            error = e.message
            throw e unless test.throws

extending faker and chance in online demo

Since version 0.1.9 it's possible to extend low-level dependencies of jsf. Online demo doesn't allow this now. Extend the gh-pages interface to allow extending jsf dependencies.

type number always generates a integer value

The following code would invariably generate an integer:
require("json-schema-faker")({type: "number"});

This can be traced to the use of random(min,max) in lib/types/number.js which in turn uses faker.random.number() with options min and max but no set precision; Faker.js's random.number() function always generates an integer value unless a precision is set in the options.

more examples in the docs

I've been trying to achieve some fake generator calls and I've spent some time on reading the source code and "trial and error" stuff, e.g. passing undefined-alike parameters to faker.js calls. Or executing RandExp from the schema.

I think the docs could include more examples. What do you think @pateketrueke? Which branch should they be included in? By the way, what is the current state of gh-pages branch - is it a work-in-progress-that-has-been-cancelled-prematurely?

A way to generate sequential date-time strings?

I'm wondering if there's a way to generate sequential date strings with a schema. I need to generate a bunch of data to be plotted on a graph. Having a bunch of random dates doesn't do me much good. Ideally, I'd like to have an array of items that are sequential time-wise.

I haven't found a way to make this happen, but maybe someone else has.

Negative integers don't work

This doesn't generate a negative integer:

{
  "type": "integer",
  "minimum": -100,
  "maximum": 0
}

Am I doing something wrong?

Please update faker.js

This project is very helpful to us. We need the new faker.js generators, such as name.jobTitle.

`Address.city` doesn't appear

I created this schema json:

{
  "title": "User",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "faker": "random.uuid"
    },
    "name": {
      "type": "string",
      "faker": "name.findName"
    },
    "login": {
      "type": "string",
      "faker": "internet.userName"
    },
    "email": {
      "type": "string",
      "format": "email",
      "faker": "internet.email"
    },
    "city": {
      "type": "string",
      "faker": "address.city"
    }
  },
  "required": [
    "id",
    "login",
    "email"
  ]
}

After generating 2000 objects I not found no one object with city field.
City field is appear If remove id, login, name or email from schema.

How to support v3

Ok it's not 'really' v3 support but good enough for my use case and works like a charm.

So just a minor tip here, in case anyone would want to use JSON Schema v3 (I want to mock up our RAML API schemas and those are only v3 as of yet).

There is an easy way to do this, the steps to take would be:

  1. npm i json-schema-compatibility
  2. read schema file(s) using any (a)sync method you like
  3. parse each file buffer -> string and apply JSON.parse to the result
  4. use the compat.v4 method and apply it on 3
  5. delete the '$schema' key from the variable holding 4

The json-schema-faker dependency normalizr (I recall) stops complaining.

A way to calculate all possible combinations of json based on a enum only json schema ?

Hello all,

Lets say i have a json schema made to describe a car.
And this json schema is only made of enum properties.
eg :
color : red, blue ,white, yellow
motorisation : 100hp, 120 hp
and so on...

Is there a way to use json-schema-faker to generate all different jsons where each json representing a unique car ?

My idea behind this, is to be able to draw a kind of tree diagram of all possible car.

Could this feature be seen as json-schema-faker some kind of major improvement?

Any answer would be welcome !

Thx by advance!

properties: type: type: 'string' throws error

{
type: 'object'
properties:
  relationship:
    type: 'string'
  type:
    type: 'string'
  title:
    type: 'string'
}

"properties.type" is causing 'unknown primitive {"type":"string"}'.

(Thanks for the error reporting update)

Is adding the faker/chance property optional?

Given a schema such as:

{
  "type": "object",
  "properties": {
     "surname": {
        "type": "string"
     }
   }
}

… json-schema-faker will happy produce something like:

{
  surname: '_b'
}

This seems to suggest adding the faker or chance property to each property is optional. Will it default to one or the other, or does it provide its own generators? If so, could you document this? (The readme suggests to me that faker/chance is mandatory).

Reference not found with $schema

Hello,

If I use a ref inside my json schema, I get a "Reference not found: http://json-schema.org/draft-04/id#" error for the $schema def.
The schema:

{ "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": 
   { "type": "object",
     "properties": 
      { "id": { "$ref": "id" },
        "name": { "$ref": "name" },
        "description": { "$ref": "description"  } },
    "required": [ "id", "name", "description" ] } }

Removing the $schema key, or remove the $refs, works, but I want to be able to keep both.

Thanks,
Omer

Generate value based on another generate value

Hello,

I have a schema, where the value of one property is oneOf different objects. I need the oneOf to be selected according to a generated value in a different field.
For example:

  "exclusiveMinimum": true,
  "items": 
   { "type": "object",
     "properties": 
      { "id": { "$ref": "id" },
        "data_item_type": { "$ref": "data_item_type" },
        "preview": { "oneOf": [
                    { "type": "object",
                      "properties": 
                        { "name": { "$ref": "name" } } },
                    { "type": "object",
                      "properties": 
                        { "duration": { "type": "number" } } }
                   ]}...

I need the preview object to be selected according to the value in data_item_type.
Is it possible?

Thank you

`number` results in `integer`

I've been trying to generate fake float cash amounts:

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

var schema = {
  "type": "object",
  "properties": {
    "floatValue": {
      "type": "number",
      "faker": {
        "finance.amount": [0, 1000000, 2]
      }
    }
  },
  "required": [
    "floatValue"
  ]
};

var sample = jsf(schema);

console.log(sample);

Each time, it results in returning a float:

{ floatValue: -60579383 }
{ floatValue: 82403714 }
{ floatValue: -88911564 }
{ floatValue: -91259973 }
{ floatValue: 55329873 }
{ floatValue: -88439479 }
{ floatValue: 26251958 }
{ floatValue: 50581325 }
{ floatValue: -32840326 }

As far as I understand the code, it is due to: https://github.com/pateketrueke/json-schema-faker/blob/master/lib/types/number.js#L8-L31

cleaning up branches

There are two branches we might not need:

Is it OK to remove them? FYI: Before releasing 0.2.1,I didn't do a merge commit (I don't like that), instead, I did a git rebase. And there were few minor conflicts I resolved. Anyway, now, when you compare those branches with master on github, you might see they're not merged in, because, literally, they're not. But their code might be there already. Therefore I need to know if I can remove them.

I can see in #65 that fix-issue-62 migt be removed,,,

BTW, The http://json-schema-faker.js.org demo page is updated to 0.2.1.

generating array of integers

I'm trying to generate many integers in an array. I've started with following fschema (i.e. faker schema 🍻):

{
  "type": "array",
  "minItems": 15,
  "items": {
    "type": "integer"
  }
}

jsf throws error and crashes: Uncaught Error: invalid range between: 15, 5 in /. It is thrown here:

  } catch (e) {
    if (e.path) {
      throw new Error(e.message + ' in ' + '/' + e.path.join('/'));
    } else {
      throw e;
    }
  }

Unfortunately, the e.path is empty and I don't know where it is. Seems like a magic number of value 5 to me. Another thing is more then minimum. I try to reduce the minItems to 5:

{
  "type": "array",
  "minItems": 5,
  "items": {
    "type": "integer"
  }
}

and I get:

[
  94859109,
  -13252038,
  -23878120,
  35945246,
  -45816780
]

(correct) or

[
  94859109,
  -13252038,
  -23878120,
  35945246,
  -45816780
]

(correct) or

[
  -72862631,
  87917025,
  34045210,
  -39725548,
  -87628962,
  36148999
]

(correct) with more than 5 elements. How is the number of elements determined? If you don't get it at first time, just click several times until you get it.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.