JSON Mock Data Generator: Fake JSON with faker.js and json-schema-faker

Generating mock JSON data means creating realistic, structured fake data for testing, prototyping, and development — without touching a real database or API. @faker-js/faker is the most widely used library for this, with 15M+ weekly npm downloads and 250+ locale-aware data types including names, emails, addresses, phone numbers, and UUIDs. Install it with npm install @faker-js/faker. This guide covers three programmatic approaches — @faker-js/faker, json-schema-faker (generate from a JSON Schema definition), and a vanilla JS fallback — plus a comparison of online tools including Mockaroo and JSON Generator. For validating and formatting the generated output, use Jsonic's JSON Formatter.

Generated mock JSON? Paste it into Jsonic's formatter to validate and pretty-print in one click.

Open JSON Formatter

Generate mock JSON with @faker-js/faker

@faker-js/faker is a TypeScript-first library that supports both ESM and CommonJS and requires Node.js 18+. It provides 60+ modules covering every common data type: people, internet, location, company, commerce, finance, lorem ipsum, dates, UUIDs, and images. Because each faker method call generates a new independent value, the idiomatic pattern for creating arrays of records is Array.from({ length: N } , createRecord) — each invocation of the factory function produces a completely new random object.

import { faker } from '@faker-js/faker'

function createMockUser() {
  return {
    id: faker.string.uuid(),
    name: faker.person.fullName(),
    email: faker.internet.email(),
    phone: faker.phone.number(),
    address: {
      street: faker.location.streetAddress(),
      city: faker.location.city(),
      country: faker.location.country(),
      zip: faker.location.zipCode(),
    },
    company: faker.company.name(),
    avatar: faker.image.avatar(),
    createdAt: faker.date.past({ years: 2 }).toISOString(),
    isActive: faker.datatype.boolean(),
  }
}

// Generate 1000 mock users
const users = Array.from({ length: 1000 }, createMockUser)
console.log(JSON.stringify(users, null, 2))

Array.from({ length: 1000 } , createMockUser) is the idiomatic pattern — each call creates a new random record. The result is a 1000-element array where every object has a unique UUID, realistic name, valid-format email, and a nested address object. Paste the output into Jsonic's JSON Formatter to validate and explore the structure. For type safety, add a return type annotation: function createMockUser(): User { ... } where User is inferred from your Zod schema or TypeScript interface.

Seeded random data for reproducible tests

faker.seed(number) fixes faker's random number generator to a deterministic state. Every subsequent faker method call in that process produces the same value in the same order — making it safe to use generated data as snapshot test fixtures. Without a seed, faker generates different values on every run, which causes snapshot tests to fail non-deterministically. Seeding solves this by making the randomness reproducible.

import { faker } from '@faker-js/faker'

faker.seed(12345)

// Always produces the same value — safe for snapshot tests
const user = {
  id: faker.string.uuid(),
  name: faker.person.fullName(),
  email: faker.internet.email(),
}
// { id: "...", name: "...", email: "..." } — identical every time seed(12345) is used

Use cases for seeded generation include Jest snapshot tests (where the fixture must match exactly across CI runs), reproducible CI test fixtures that need to be committed to version control, and debugging — when a test fails with a specific seed you can reproduce the exact data locally. To isolate seed state between test cases, call faker.seed(testIndex) at the start of each test so they don't share the same RNG sequence. For parallel test runners, create a separate faker instance per worker: new faker.Faker({ locale: [en] }) with its own .seed() call.

Generate mock JSON from a JSON Schema with json-schema-faker

json-schema-faker takes a JSON Schema definition and generates mock data that conforms to it. This is useful when you already have a JSON Schema for your API or data model and don't want to write a separate faker template that could drift out of sync. Install with npm install json-schema-faker. It supports JSON Schema drafts 04, 06, 07, 2019-09, and 2020-12, and uses @faker-js/faker internally to generate realistic values for named formats like email, date-time, and uuid. For schemas with $ref references, use jsf.resolve(schema) (returns a Promise) instead of jsf.generate(schema).

import jsf from 'json-schema-faker'

const schema = {
  type: 'object',
  properties: {
    id: { type: 'integer', minimum: 1, maximum: 9999 },
    username: { type: 'string', minLength: 3, maxLength: 20 },
    email: { type: 'string', format: 'email' },
    score: { type: 'number', minimum: 0, maximum: 100 },
    tags: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 5 },
  },
  required: ['id', 'username', 'email'],
}

// Generate a single record
const record = jsf.generate(schema)

// Generate 50 records
const records = Array.from({ length: 50 }, () => jsf.generate(schema))
console.log(JSON.stringify(records, null, 2))

json-schema-faker respects all schema constraints: minimum, maximum, minLength, maxLength, minItems, maxItems, enum, const, and required. Generated values for format: "email" are realistic email addresses, not random strings. For writing schemas that json-schema-faker can use, see our JSON Schema guide and our guide to validate JSON Schema in JavaScript with Ajv.

Vanilla JavaScript mock data generator (no dependencies)

For simple use cases where installing a library is not practical — browser scripts, restricted environments, or minimal projects — Math.random() combined with a few helper functions covers most needs. This approach produces less realistic data (names come from a fixed list rather than locale-aware generation) but has zero dependencies and works in any JavaScript environment including browsers and older Node.js versions.

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

function randomItem(arr) {
  return arr[Math.floor(Math.random() * arr.length)]
}

const statuses = ['active', 'inactive', 'pending']
const domains = ['gmail.com', 'yahoo.com', 'outlook.com']

function generateRecord(i) {
  const firstName = randomItem(['Alice', 'Bob', 'Carol', 'David', 'Eve'])
  const lastName = randomItem(['Smith', 'Jones', 'Lee', 'Brown', 'White'])
  return {
    id: i + 1,
    name: `${firstName} ${lastName}`,
    email: `${firstName.toLowerCase()}.${randomInt(1, 999)}@${randomItem(domains)}`,
    age: randomInt(18, 65),
    status: randomItem(statuses),
    createdAt: new Date(Date.now() - randomInt(0, 365 * 24 * 60 * 60 * 1000)).toISOString(),
  }
}

const dataset = Array.from({ length: 100 }, (_, i) => generateRecord(i))
console.log(JSON.stringify(dataset, null, 2))

This approach produces less realistic data but has zero dependencies and works in any JS environment including browsers. For a UUID without dependencies, use the Web Crypto API: crypto.randomUUID() is available in all modern browsers and Node.js 14.17+. To extend this pattern with more realistic data, swap the fixed name arrays for larger datasets loaded from a JSON file, or add locale-specific name lists as plain arrays.

Online JSON mock data generator tools compared

Several online tools generate mock JSON without writing code. Each has different trade-offs around free tier limits, supported formats, and input method. Programmatic approaches (faker.js, json-schema-faker) offer unlimited records and integrate into automated workflows; GUI tools like Mockaroo are faster for one-time manual downloads. Use Jsonic's JSON Formatter to validate any generated output before using it in your tests.

ToolFree tierFormatsRealistic dataJSON Schema input
Mockaroo1,000 rows/downloadJSON, CSV, SQL, ExcelYesNo
JSON GeneratorUnlimitedJSONVia template syntaxNo
json-schema-faker (npm)UnlimitedJSONModerateYes
@faker-js/faker (npm)UnlimitedAnyExcellent (250+ types)No

All programmatic approaches run in Node.js; faker.js also works in modern browsers via ESM imports. Mockaroo and JSON Generator are browser-only GUI tools with no programmatic API in the free tier. For automated test pipelines, @faker-js/faker is the clear choice — it integrates directly into Jest, Vitest, or any Node.js test runner and supports seeded generation for reproducible fixtures.

Generate nested JSON mock data

Real API responses often have nested arrays and objects — pagination wrappers, embedded reviews, related entities. faker.js handles this naturally because each faker call is independent: you can nest Array.from() calls to generate sub-arrays of variable length. The example below simulates a paginated API response with products, each containing a variable number of embedded reviews.

import { faker } from '@faker-js/faker'

function generateApiResponse(page = 1, perPage = 10) {
  return {
    page,
    perPage,
    total: 500,
    data: Array.from({ length: perPage }, () => ({
      id: faker.string.uuid(),
      product: faker.commerce.productName(),
      price: parseFloat(faker.commerce.price()),
      category: faker.commerce.department(),
      inStock: faker.datatype.boolean(),
      reviews: Array.from({ length: faker.number.int({ min: 0, max: 5 }) }, () => ({
        rating: faker.number.int({ min: 1, max: 5 }),
        comment: faker.lorem.sentence(),
        reviewer: faker.person.firstName(),
      })),
    })),
  }
}

console.log(JSON.stringify(generateApiResponse(1, 5), null, 2))

The key detail is faker.number.int({ min: 0, max: 5 }) as the length argument to the inner Array.from() — this gives each product a random number of reviews between 0 and 5, mirroring real API variability. Use Jsonic's JSON Validator to confirm the output is well-formed before wiring it into your test suite. For validating the structure against a schema, see our guide on validate JSON Schema in JavaScript with Ajv.

Frequently asked questions

What is the best library for generating fake JSON data in JavaScript?

@faker-js/faker is the most popular library for generating fake JSON data in JavaScript, with 15M+ weekly npm downloads and 250+ data types. It supports names, addresses, emails, phone numbers, dates, UUIDs, credit cards, images, lorem ipsum, company names, product names, and much more. Install with npm install @faker-js/faker. It works in Node.js 18+, Deno, and modern browsers, and supports ESM and CommonJS. For TypeScript projects, @faker-js/faker ships its own type definitions — no @types package needed. Alternative libraries include Chance.js (lighter, 8KB gzipped), casual (simpler API), and Bogus (.NET port). For generating mock data from a JSON Schema definition, use json-schema-faker instead, which integrates with @faker-js/faker internally for realistic values.

How do I generate mock JSON data from a JSON Schema?

Use the json-schema-faker npm package: npm install json-schema-faker. Pass your JSON Schema object to jsf.generate(schema) to get a single random record that conforms to the schema. For arrays of records, wrap it in Array.from({ length: N } , () => jsf.generate(schema)). json-schema-faker supports JSON Schema drafts 04, 06, 07, 2019-09, and 2020-12, including $ref references, format keywords (email, date-time, uuid), enum, const, and required. By default it uses Faker.js internally for realistic values when the schema specifies formats. For complex schemas with $ref, call jsf.resolve(schema) instead of jsf.generate() — it returns a Promise that resolves all references first. See our JSON Schema guide for writing schemas that json-schema-faker can use.

How do I generate 1000 fake JSON records in Node.js?

Use Array.from({ length: 1000 } , createRecord) where createRecord is a function that returns one object using @faker-js/faker. Each call to the function creates a new independent random record because faker.js generates new random values on each call. Example: const records = Array.from({ length: 1000 }, () => ({ id: faker.string.uuid(), name: faker.person.fullName(), email: faker.internet.email() })). This pattern is faster than a for loop and avoids off-by-one errors. For 10,000+ records, the generation completes in under 200ms in Node.js. To write the output to a file, use fs.writeFileSync("data.json", JSON.stringify(records, null, 2)). For NDJSON (one JSON object per line), use records.map(r => JSON.stringify(r)).join('\n') instead.

What is the difference between Mockaroo and @faker-js/faker?

Mockaroo is an online service where you configure fields through a GUI and download data as JSON, CSV, SQL, or Excel — no code required, but limited to 1,000 rows per download in the free tier. @faker-js/faker is an open-source npm library you run in your own code — unlimited records, fully programmable, reproducible with seeds, and integrates directly into test suites. Mockaroo is better for one-time dataset downloads without coding. @faker-js/faker is better for automated tests, CI pipelines, and applications that need fresh mock data on every test run. Mockaroo also offers a paid Mock API feature for simulating API endpoints. @faker-js/faker supports 70+ locales, so faker.person.fullName() can return realistic German, Japanese, or Spanish names by setting faker.locale = "de".

How do I use a seed for reproducible fake JSON data?

Call faker.seed(number) before generating data. A seed is an integer that initializes faker's random number generator to a fixed state — every subsequent call to any faker method will produce the same sequence of values. Example: faker.seed(42); const name = faker.person.fullName() always returns the same name, no matter how many times you run it. This is critical for snapshot tests: if your test fixture needs to produce the same JSON every time, use a fixed seed. Reset the seed between test cases if each test needs different but still deterministic data: faker.seed(testIndex). Note that seeding is instance-scoped — new faker.Faker({ locale: [en] }) with .seed(42) is isolated from the global faker import. Use instance-based faker for parallel test runners to avoid seed collisions.

Can I generate fake JSON data without installing any library?

Yes. For simple use cases, Math.random() combined with a few helper functions covers most needs: Math.floor(Math.random() * max) for integers, picking from an array with arr[Math.floor(Math.random() * arr.length)], and new Date(Date.now() - Math.random() * 365 * 86400000).toISOString() for random past dates. This approach has zero dependencies and works in any JavaScript environment including browsers. The downside is that the generated data is less realistic — names like "Alice Smith" from a fixed list, not locale-aware. For browser-based generation without npm, the Crypto Web API provides cryptographically secure random values: crypto.randomUUID() generates a standard v4 UUID in all modern browsers. For more realistic browser-based data without npm, use a CDN-linked version of @faker-js/faker via <script type="module"> with an import map.

Generated mock JSON? Paste it into Jsonic's formatter to validate and pretty-print in one click.

Open JSON Formatter