Mock JSON Data: What It Is and How to Generate It

By the JSONGenerator team · Published
Almost every project needs data before it has any. The frontend is ready before the API, the API is ready before the database has users, and the tests need records that nobody wants to type out by hand. Mock JSON data fills that gap.
This guide covers what mock data is, when it's the right choice, what separates useful mock data from filler, and three ways to generate it. It then shows how to serve the result as a mock API, keep it as test fixtures, and turn it into types and schemas.
What is mock JSON data?
Mock JSON data is made-up data in JSON format that has the same shape as the real thing: the same keys, nesting and value types your API or database returns, filled with plausible but fake values. You use it to build interfaces, test code and demo features before real data exists, or when real data can't be used.
You'll also see it called fake JSON data, dummy JSON data or sample JSON data. The terms overlap. "Sample" sometimes means a small, hand-picked example for documentation, and "mock" often means a stand-in for a specific API response, but in practice they all describe the same thing: JSON that looks real and isn't.
A single mock record for a user might look like this:
{
"id": "185ed782-b462-4f93-9fed-e04e1bfca6ff",
"firstName": "Westley",
"lastName": "Keeling",
"email": "German_Purdy@example.com",
"role": "editor",
"active": true,
"createdAt": "2023-11-11T17:29:29.699Z"
}
Nothing here belongs to a real person, but a user list, a profile page or a validation function can't tell the difference. That's the point.
When should you use mock data?
Mock data is the default for anything that runs outside production: local development, automated tests, demos, documentation and design reviews. The common alternatives are copying production data or using an anonymised copy of it. Each has a place, and the trade-offs look like this:
| Criterion | Mock JSON data | Anonymised production copy | Production data |
|---|---|---|---|
| Contains real personal data | No | Reduced, but records can sometimes be re-identified | Yes |
| Available before the feature ships | Yes | No, the data has to exist first | No |
| Reflects real-world quirks and distributions | Only what you design in | Mostly | Fully |
| Safe for CI logs, demos and public repos | Yes | Depends on how well it was anonymised | No |
| Effort to set up | Low | High: masking rules, review, refreshes | Low, but access controls and audits add cost |
| Easy to regenerate after a schema change | Yes | No | Not applicable |
| Best for | Development, tests, prototypes, docs | Performance and migration rehearsals | Production only |
The short version: use mock data unless you specifically need the messiness of real data. The cases where you do are narrow. Reproducing a bug that only shows up with one customer's records, rehearsing a data migration, and tuning query performance on realistic volumes are all good reasons to work with real or anonymised data, under the access controls that data requires.
For everything else, mock data is faster to get, carries no privacy risk, and can contain exactly the cases you want to test rather than whatever happened to be in the database last Tuesday.
What makes mock data realistic and useful?
Random values in the right keys are a start, but mock data earns its keep when it behaves like real data in the ways your code cares about. Five properties matter most.
Shape
The keys, nesting and array structure should match the real API or table exactly. If the real response wraps results in a data array with paging fields, the mock should too. A mock that's flatter or tidier than production hides the code you'll have to write later.
Types
JSON has six kinds of value: strings, numbers, booleans, null, objects and arrays (RFC 8259). A mock that returns "42" where the API returns 42, or "true" where it returns true, will pass a visual check and fail in code. JSON has no date type, so dates are almost always ISO 8601 strings such as "2025-09-02T00:36:26.745Z". Match whatever your API actually sends.
Edge cases
Real data has empty arrays, null optional fields, very long names, names with apostrophes and accents, zero balances and orders with fifty line items. Mock data that only contains the happy path tests only the happy path. Build in the awkward cases on purpose: a field that is sometimes null, an array that is sometimes empty, a status value that's rare in production but has its own code path.
Volume
Five records won't show you that a table needs pagination or that a list re-renders slowly. Five thousand will slow down your test suite. Pick the volume for the job: a handful of records for unit tests, tens to a few hundred for integration tests and UI work, and a separate, larger data set for load testing.
Determinism
Tests need the same data on every run. If a fixture is regenerated each time, a test can pass on one run and fail on the next for reasons unrelated to the code. Either generate the data once and commit the file, or use a generator that accepts a fixed seed. More on this in the fixtures section below.
How do you generate mock JSON data?
There are three common approaches. They differ mostly in how much code you want to own.
| Approach | Good for | Drawbacks |
|---|---|---|
| Writing JSON by hand | A few records, documentation examples, exact edge cases | Slow, small, and tends to be unrealistic ("Test User 1") |
| A Faker script | Large or seeded data sets, generation inside a test run | You write and maintain code for every shape |
| A template-based generator | Quick, realistic data from a description of the shape | Less control than code; no fixed seed in JSONGenerator |
By hand
Writing JSON yourself is fine for two or three records, or for a specific edge case you want to pin down exactly, such as a user with an empty roles array. It doesn't scale past that, and hand-written data drifts toward the same few tidy values.
With a Faker script
Faker is a JavaScript library that produces realistic names, addresses, emails, dates, product names and much more. You write a script that builds the objects and writes them to a file:
import { writeFileSync } from "node:fs";
import { faker } from "@faker-js/faker";
faker.seed(42); // same seed, same data on every run
const users = Array.from({ length: 20 }, () => ({
id: faker.string.uuid(),
firstName: faker.person.firstName(),
lastName: faker.person.lastName(),
email: faker.internet.email(),
createdAt: faker.date.past().toISOString(),
}));
writeFileSync("users.json", JSON.stringify(users, null, 2));
This is the right choice when you need generation inside a test run, very large data sets, or logic that's hard to express any other way. The cost is that every shape is code you maintain.
With a template (JSONGenerator)
A template-based generator lets you describe the shape you want as JSON and fills in the values for you. In JSON Generator, each value in your template is a fixed value, a template tag, or text that contains tags. Tags look like function calls, such as firstName(), email(example.com) or int(0, 500). The full list, with example output for each tag, is in the template tag reference.
Here's a template for 20 user records:
{
"users": [
"repeat(20)",
{
"id": "guid()",
"firstName": "firstName()",
"lastName": "lastName()",
"fullName": "this.firstName this.lastName",
"email": "email(example.com)",
"role": "enum(admin, editor, viewer)",
"active": "enum(true, false)",
"loginCount": "int(0, 500)",
"balance": "double(0, 5000, 2)",
"createdAt": "date(2023-01-01, 2025-12-31)",
"address": {
"city": "city()",
"country": "country()"
}
}
]
}
And the first two records of one run:
{
"users": [
{
"id": "185ed782-b462-4f93-9fed-e04e1bfca6ff",
"firstName": "Westley",
"lastName": "Keeling",
"fullName": "Westley Keeling",
"email": "German_Purdy@example.com",
"role": "editor",
"active": true,
"loginCount": 470,
"balance": 236.18,
"createdAt": "2023-11-11T17:29:29.699Z",
"address": {
"city": "Blandafort",
"country": "Christmas Island"
}
},
{
"id": "4154602d-013c-48d1-99f2-f78492bf696d",
"firstName": "Eve",
"lastName": "Lakin",
"fullName": "Eve Lakin",
"email": "Dana.Daugherty@example.com",
"role": "admin",
"active": false,
"loginCount": 113,
"balance": 4181.83,
"createdAt": "2025-10-07T13:09:45.141Z",
"address": {
"city": "Apple Valley",
"country": "Liechtenstein"
}
}
]
}
A few things worth knowing about how the template works:
repeat()controls volume. As the first item of an array, it repeats the item that follows.repeat(20)gives exactly 20,repeat(5,10)picks a count between 5 and 10, andrepeat()with no arguments picks between 1 and 100. The count is capped at 300. See repeat in the docs.- Types are preserved. A tag used as the whole value returns a typed value:
int(0, 500)gives the number470, not the string"470", andenum(true, false)gives a real boolean. Inside other text, a tag is inserted as text, so"ORD-int(10000, 99999)"produces a string like"ORD-39689". - Fields can reference each other.
this.firstNamerefers to a value generated earlier in the same object, sofullNamealways matchesfirstNameandlastName. Nested objects can also reference fields of the object that contains them; see field references. email(example.com)keeps addresses safe. Every address ends inexample.com, a domain reserved for documentation and testing, so a test that sends an email by mistake can't reach a real inbox.
Output can be copied or downloaded as JSON, CSV or YAML. Generation runs entirely in your browser, and your templates are kept in your browser's local storage, so nothing is uploaded. If you'd rather start from something ready-made, the examples page has templates for user profiles, e-commerce orders, product catalogs, addresses, flight bookings, network logs and an employee directory.
Nested data and relationships
Real APIs return nested data: orders with line items, posts with comments. Templates handle that with a repeat() inside a nested array. This template also builds in two edge cases, a coupon code that is sometimes null and a varying number of line items:
{
"orders": [
"repeat(5,10)",
{
"id": "guid()",
"number": "ORD-int(10000, 99999)",
"status": "enum(pending, paid, shipped, refunded)",
"couponCode": "enum(null, SPRING10, WELCOME5)",
"placedAt": "date(2025-01-01, 2025-12-31)",
"items": [
"repeat(1,4)",
{
"orderId": "this.id",
"product": "productName()",
"quantity": "int(1, 5)",
"unitPrice": "double(5, 250, 2)"
}
]
}
]
}
One order from the output:
{
"id": "d9ca2243-8419-4259-b156-258f5c25342c",
"number": "ORD-39689",
"status": "pending",
"couponCode": "SPRING10",
"placedAt": "2025-09-02T00:36:26.745Z",
"items": [
{
"orderId": "d9ca2243-8419-4259-b156-258f5c25342c",
"product": "Practical Steel Tuna",
"quantity": 2,
"unitPrice": 82.41
}
]
}
Inside each line item, this.id resolves to the parent order's id, so every item points back at the order it belongs to. enum() returns null, true, false and numbers as real JSON values, which is how couponCode can be either a string or null.
How do you serve mock JSON as a mock API?
A JSON file on disk is useful for tests. For frontend work you usually want something you can fetch, with real URLs and HTTP methods. json-server turns a JSON file into a REST API with one command.
Generate the users template above, download the result as JSON and save it as db.json. Each top-level key becomes a resource, so users becomes /users. You can put several resources in one file by adding more top-level keys, for example users and orders side by side.
Then start the server:
npm install json-server
npx json-server db.json
It listens on http://localhost:3000 by default and gives you the usual routes for each array resource:
GET /usersandGET /users/:idPOST /usersPUT /users/:idandPATCH /users/:idDELETE /users/:id
json-server expects each record to have an id, and treats ids as strings. The guid() tag gives each user a unique string id, which works without any changes. Query parameters such as _sort, _page and _per_page cover sorting and pagination; run npx json-server --help for the options your installed version supports.
Your frontend code can now call it like the real API:
type User = {
id: string;
firstName: string;
lastName: string;
email: string;
role: "admin" | "editor" | "viewer";
active: boolean;
};
const API_URL = "http://localhost:3000";
export async function getUser(id: string): Promise<User> {
const res = await fetch(`${API_URL}/users/${id}`);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
When the real API is ready, change API_URL and nothing else. Two things to keep in mind:
- json-server writes changes back to the file. A
POSTorDELETEeditsdb.json. Keep a clean copy in version control and restore it when you want a fresh start. - It returns its own response shape. If your real API wraps records in an envelope, adds headers, or returns specific error formats, json-server won't match that out of the box. For a single fixed response, a static file with the exact shape is often simpler.
For that second case, template the whole response, envelope included:
{
"page": 1,
"perPage": 10,
"total": "int(30, 200)",
"data": [
"repeat(10)",
{
"id": "int(1, 10000)",
"name": "companyName()",
"website": "url()",
"city": "city()"
}
]
}
Fixed values like "page": 1 pass through unchanged, so you get a mock API response with the real paging fields and ten generated records:
{
"page": 1,
"perPage": 10,
"total": 42,
"data": [
{
"id": 4011,
"name": "Haag Inc",
"website": "https://jaunty-priesthood.org/",
"city": "Fort Belle"
},
{
"id": 1102,
"name": "Nicolas LLC",
"website": "https://portly-innovation.name/",
"city": "Toniport"
}
]
}
Save it in your frontend's static folder, or return it from whatever request-mocking tool your test setup already uses.
How do you use mock JSON as test fixtures?
A fixture is a fixed set of data a test runs against. Generated JSON makes good fixtures, with one rule: commit the generated file, not just the template. JSON Generator produces different values on every run and has no seed option, so regenerating inside the test run would give you different data each time. Generate once, review the output, and save it next to your tests, for example as test/fixtures/users.json.
Then import it in the test. With resolveJsonModule enabled in tsconfig.json, TypeScript can import JSON files directly:
import { describe, expect, it } from "vitest";
import users from "./fixtures/users.json";
import { activeUsers } from "../src/users";
describe("activeUsers", () => {
it("returns only active users", () => {
const result = activeUsers(users.users);
expect(result.every((user) => user.active)).toBe(true);
});
});
When the schema changes, update the template, regenerate, and commit the template and the new fixture in the same pull request. Keeping the template in the repo, for example as test/fixtures/users.template.json, means the next person can regenerate without guessing how the file was made.
The same fixtures can seed a database. The JSON to SQL converter turns a JSON array into CREATE TABLE and INSERT statements for PostgreSQL, MySQL, SQLite or SQL Server, and JSON to CSV produces a file most databases and spreadsheets can import. For a full pipeline, the guide to seeding test databases in CI/CD walks through a seed script and a GitHub Actions workflow that loads generated fixtures into a fresh Postgres database on every run.
How do you turn mock JSON into types or schemas?
Once you have a realistic sample, you can derive the contract from it instead of writing it by hand.
- JSON Schema. Paste a record into the JSON Schema Generator to get a schema with types and required fields. You can then validate your fixtures, or real API responses, against it, which catches the day someone changes a number to a string.
- TypeScript types. The JSON to TypeScript converter produces interfaces, including nested types, from the same sample. That gives your mock API client and your tests a type to check against.
There are also converters for Go, Java, C#, YAML, XML and other formats. If you're choosing a format for config or fixtures, the comparisons of YAML vs JSON and Protobuf vs JSON cover the trade-offs.
One caution: a schema or type inferred from mock data describes the mock data. If your template never produces null for a field, the inferred schema will say the field is always present. Check the result against what the real API can return, and add optional fields and nullable types where needed.
Common pitfalls
Mocks that drift from the real API. The API adds a field or renames one, the mock doesn't, and the frontend works locally and breaks in staging. Validate mocks against the same schema the API uses, and regenerate when the contract changes.
Only the happy path. Every user is active, every order has one item, every optional field is filled. Use enum() with null and with rare values, and vary array lengths with repeat(min,max), so edge cases show up in the data rather than in production.
Strings where numbers belong. "price": "19.99" and "price": 19.99 are different values. Check the types in your mock match the API, not just the values.
Random data in assertions. A test that asserts expect(user.firstName).toBe("Westley") against freshly generated data will fail on the next run. Commit fixtures, or assert on properties ("every result is active") rather than specific generated values.
Duplicate values in unique fields. Random data can repeat. Emails and usernames drawn from a finite list of names will occasionally collide, which matters when the data goes into a column with a unique constraint. Use guid() for ids and check unique fields before committing a fixture.
Dates that go stale. A fixture with an "upcoming" appointment on a fixed date stops being upcoming once that date passes. Keep relative dates out of fixtures and set them in test setup code instead.
Real data sneaking in. Pasting "just one" real customer record into a fixture puts personal data in your repository and its history. Keep mock data fully synthetic, and use email(example.com) or another reserved domain for addresses.
Summary
Mock JSON data is fake data with the real shape: same keys, same nesting, same types. It lets you build and test before the real data exists, and keeps personal data out of development, CI and demos.
- Use it by default outside production, and reach for real or anonymised data only for the narrow cases that need it.
- Make it useful by matching shape and types exactly, building in edge cases, choosing the right volume, and keeping it deterministic.
- Generate it by hand for a few records, with Faker when you need code and seeds, or from a template in JSON Generator for realistic data in seconds.
- Serve it with json-server for a quick REST API, or as a static file when you need an exact response shape.
- Commit generated fixtures next to the template that made them, and derive JSON Schema and TypeScript types from them to keep mocks and the real API in step.