Awesome Go

fejkdata

CategoryMiscellaneous
SubcategoryUncategorized
Stars1

CLI and library that render fake test data from JSON templates, with related values that match

About fejkdata

This large README is shown as a plain-text preview. Read the full README at the source

# fejkdata

[![Go Reference](https://pkg.go.dev/badge/github.com/larvit/fejkdata.svg)](https://pkg.go.dev/github.com/larvit/fejkdata)
[![Tests](https://github.com/larvit/fejkdata/actions/workflows/test.yml/badge.svg)](https://github.com/larvit/fejkdata/actions/workflows/test.yml)
[![Coverage](https://coveralls.io/repos/github/larvit/fejkdata/badge.svg?branch=main)](https://coveralls.io/github/larvit/fejkdata?branch=main)
[![Release](https://img.shields.io/github/v/release/larvit/fejkdata)](CHANGELOG.md)

Fake data for tests. Related values match, like a postcode and its city. CSV, SQL or JSON.

Most fake data is a bag of unrelated values. You get a man named Anna, a postal code from
another town and an id that no checker accepts. fejkdata is a CLI, a Go library, a Python package and
an npm package. Its values fit together, so a row still passes when your code checks it. Docs and
examples: [fejkdata.dev](https://fejkdata.dev).

```sh
brew install larvit/tap/fejkdata
echo '{/sv_SE.person}' | fejkdata    # Sara Eriksson
```

`person.json`, the eleven-line template under [CSV and SQL seed data](#csv-and-sql-seed-data),
fills a file with rows like the one below:

```sh
fejkdata --format csv --repeat 1000000 < person.json > people.csv
fejkdata --format sql --table people --repeat 1000000 < person.json > people.sql
```

```text
sex,first,last,personnummer,email,street,postal-code,locality
kvinna,Vira,Larsson,501120-2388,[email protected],Kärrvägen 1,831 73,Östersund
```

What sets it apart:

1. **Correlated fields.** The template draws a sex, a last name and an address once each.
   Every column reads those draws. Vira is a woman's name and `kvinna` is Swedish for
   woman. The personnummer is Sweden's national id, and this one is a woman's. 831 73 is a
   postal code of Östersund.
2. **Valid national ids where possible, from a test series where the issuer keeps one.**
   The personnummer passes its check digit. It comes from the series the Swedish Tax Agency
   keeps for tests. Norwegian, Finnish and German ids come from such a series too. A few
   strict checkers refuse those. Other countries' ids are valid and may be a living person's.
   [Shipped data](#shipped-data) says which countries' ids come from a test series, and
   which checker refuses which.
3. **CSV and SQL test data from one template.** The same JSON template prints one value or
   a million rows of seed data. The formats are CSV, SQL `INSERT`s, PostgreSQL `COPY`, JSON
   and NDJSON. One binary carries the data. It has no dependencies and fetches nothing.
4. **Errors that explain the fix.** A mistake in a template stops the run before the first
   row, with exit 2. The error says what is wrong, and many say how to fix it.
   `{sv_SE.person}` fails with `write {/sv_SE.person} to reference the data`. A coding agent
   fixes that in one retry.

US English, Swedish, German, French and the other [locales](#shipped-data) each ship
persons, addresses, national ids, phone numbers, companies, emails and dates. Beyond the data:

- **Go structs:** `FakeStruct` fills a struct from its `fake:"…"` tags ([Go tests](#go-tests)).
- **Your own data:** each JSON file in a folder you pass adds a path, such as
  `{/acme.customer}`, and a mistake in it fails at load, never mid-render.
- **Reproducible:** the same seed, date, data and versions give the same output, when one goroutine
  draws it.

Where each task starts:

| I want to | Start at |
|---|---|
| Fill a database with a million rows | [CSV and SQL seed data](#csv-and-sql-seed-data), then [Load into a database](#load-into-a-database) |
| Fill a Go struct | [Go tests](#go-tests) |
| Use it from Python | [Python tests](#python-tests) |
| Use it from JavaScript or TypeScript | [JavaScript and TypeScript tests](#javascript-and-typescript-tests) |
| Get a few values at a shell | [CLI](#cli) |
| Write several linked templates in one run | [Linked templates](#linked-templates), and in Go [Linked templates in Go](#linked-templates-in-go) |
| Link one table's rows to another's by key | [Linked tables](#linked-tables) |
| Find a path | [Every shipped path](#every-shipped-path) |
| See which ids a strict checker refuses | [Shipped data](#shipped-data) |
| Add my own data | [Your own data](#your-own-data), then [Data format](#data-format) |
| Ship my own CLI | [Your own CLI](#your-own-cli) |
| Set up a coding agent, or fix a template from its error | [For coding agents](#for-coding-agents) |
| Add a locale | [Add a locale](#add-a-locale) |

[Why fejkdata](#why-fejkdata) · [Install](#install) · [Quick start](#quick-start) · [CLI](#cli) · [Library](#library) · [Data](#data) · [Data format (templates)](#data-format) ·
[Functions](#functions) · [Versioning](#versioning) · [Audience](#audience) ·
[Goals](#goals) · [Development](#development) · [License](#license)

## Why fejkdata

| | fejkdata | [Faker](https://fakerjs.dev) (JavaScript) | [gofakeit](https://github.com/brianvoe/gofakeit) | [Mockaroo](https://www.mockaroo.com) |
|---|---|---|---|---|
| Correlated fields | One named draw feeds every field that reads it | "all properties are just randomly generated" until your code passes one result to the next call, as in `firstName(sex)` | A template binds one `Person` and reads its fields; the docs don't say that a struct tag can read another tag's draw | First name, gender, last name, email and username agree, and a formula reads other fields |
| Valid national ids where possible, and postal codes that match the town | Ids for ten countries, four from the issuer's test series; a postal code of the address's own town | No national id; `zipCode` takes a state, not a city | `SSN` and `EIN`, each "a random" number; the docs don't say that `Zip` matches `City` | Country, city, state and postal code agree; the pages read name no national id |
| CSV and SQL test data | One template and one command: CSV, SQL, `COPY`, JSON, NDJSON, up to 1,048,576 rows a run | No CLI and no file output: "you most likely need to write a factory function" | Go functions `CSV`, `JSON`, `XML` and `SQL`; its CLI runs one function, `-loop` times | CSV, JSON, SQL and Excel; 1,000 rows a file on the free plan, 10 million on the largest hosted one |
| Errors | Before the first row, naming what is wrong; a mistake in a template exits 2 | Thrown at run time where a locale lacks the data; "we don't have dedicated error messages for wrong parameter types" | `Template`, `CSV` and `SQL` return an `error`; the docs don't say when | The pages read don't say |
| Install | Homebrew, Scoop, apt, dnf, apk, Docker, `go install`, `pip install`, `npm install` | `npm install @faker-js/faker` | `go get`, and `go install` for the CLI | Nothing to install: hosted on mockaroo.com, with a Docker image on the Enterprise plan |
| Runtime | One binary, a Go library, a Python package or an npm package; no network | Node.js 20 or above, or a browser | A Go program, or its CLI | Its web service, or its API with a key |

Each cell states what the tool's own docs said on 2026-11-21. Where a cell says the docs don't
say, these are the pages read. Faker: [Getting started](https://fakerjs.dev/guide/), [Usage](https://fakerjs.dev/guide/usage),
[Localization](https://fakerjs.dev/guide/localization), [the API index](https://fakerjs.dev/api/) and its
[Person](https://fakerjs.dev/api/person) and [Location](https://fakerjs.dev/api/location) pages. gofakeit: its
[README](https://github.com/brianvoe/gofakeit#readme), [its CLI's README](https://github.com/brianvoe/gofakeit/tree/master/cmd/gofakeit)
and [the package documentation](https://pkg.go.dev/github.com/brianvoe/gofakeit/v7). Mockaroo: its
[front page](https://www.mockaroo.com), [help](https://www.mockaroo.com/help), [formulas](https://www.mockaroo.com/help/formulas),
[API docs](https://www.mockaroo.com/docs) and [pricing](https://www.mockaroo.com/pricing).

## Install

```sh
brew install larvit/tap/fejkdata                                  # macOS, Linux
scoop bucket add larvit https://github.com/larvit/scoop-bucket && scoop install fejkdata  # Windows
docker run --rm -i larvit/fejkdata < template.json                # any OS with Docker
go install github.com/larvit/fejkdata/cmd/fejkdata@latest         # any OS with Go
```

On shared CI runners, pull `ghcr.io/larvit/fejkdata` instead: Docker Hub limits anonymous
pulls per IP address.

Debian, Ubuntu, Fedora, RHEL and Alpine install from fejkdata's signed repositories, which
hold the latest release:

```sh
# Debian, Ubuntu
sudo curl -fsSLo /etc/apt/keyrings/fejkdata.asc https://larvit.github.io/fejkdata/fejkdata.asc
echo 'deb [signed-by=/etc/apt/keyrings/fejkdata.asc] https://larvit.github.io/fejkdata/deb stable main' | sudo tee /etc/apt/sources.list.d/fejkdata.list
sudo apt update && sudo apt install fejkdata

# Fedora, RHEL
sudo curl -fsSLo /etc/yum.repos.d/fejkdata.repo https://larvit.github.io/fejkdata/rpm/fejkdata.repo
sudo dnf install fejkdata

# Alpine, as root
wget -qO /etc/apk/keys/fejkdata.rsa.pub https://larvit.github.io/fejkdata/apk/fejkdata.rsa.pub
echo https://larvit.github.io/fejkdata/apk >> /etc/apk/repositories
apk add fejkdata
```

Each [release](https://github.com/larvit/fejkdata/releases) also carries the binaries for
Linux, macOS and Windows on amd64 and arm64, and the `.deb`, `.rpm` and `.apk` packages.
The binaries are unsigned. macOS refuses to run one a browser downloaded until you run
`xattr -d com.apple.quarantine fejkdata`.

From Python, `pip install fejkdata` installs the package that [Python tests](#python-tests)
shows. It carries the CLI but doesn't put a `fejkdata` command on your path.

From JavaScript or TypeScript, `npm install @larvit/fejkdata` installs the package that
[JavaScript and TypeScript tests](#javascript-and-typescript-tests) shows. It downloads 19 MB
and unpacks to 69 MB: fejkdata built to WebAssembly, with all the shipped data.

## Quick start

### CSV and SQL seed data

Save this record as `person.json`. Its `format` draws one sex, one last name and one address, and each column reads those same draws, so a row's name, sex, personnummer, email and address agree. [Records](#records) explains the record.

```json
{
  "format": "{/sv_SE.sex as s}{/sv_SE.last-name as l}{/sv_SE.address as a}",
  "sex": "{s.name}",
  "first": "{s.first-name}",
  "last": "{l}",
  "personnummer": "{s.personnummer}",
  "email": "{slugify(s.first-name)}.{slugify(l)}@example.com",
  "street": "{a.street} {a.street-number}",
  "postal-code": "{a.postal-code}",
  "locality": "{a.locality}"
}
```

```sh
fejkdata --seed 1 --today 2026-01-15 --format csv < person.json    # a header, then one person, the same every day
fejkdata --format csv --repeat 1000000 < person.json > people.csv  # a million rows
fejkdata --format sql --table people --repeat 1000000 < person.json > people.sql
```

The first command prints:

```text
sex,first,last,personnummer,email,street,postal-code,locality
kvinna,Vira,Larsson,501120-2388,[email protected],Kärrvägen 1,831 73,Östersund
```

A fixture this size repeats personnummer and email values. [Personnummer](docs/locales/sv_SE.md#personnummer-and-samordningsnummer) explains why a personnummer repeats. On MySQL or MariaDB, [Records](#records) says what to set before the SQL loads.

### Go tests

Declare the struct, and `FakeStruct` fills it from its tags. A tag binds a draw with `as`, such as `{/sv_SE.sex as s}`, and the other tags read that draw in any field order, so the fields agree. [Names](#names) explains `as`; [Library](#library) covers the rest of the API.

```go
package signup

import (
	"testing"
	"time"

	"github.com/larvit/fejkdata"
	svse "github.com/larvit/fejkdata/data/sv_SE"
)

type Person struct {
	Sex          string `fake:"{/sv_SE.sex as s}{s.name}"`
	First        string `fake:"{s.first-name}"`
	Last         string `fake:"{/sv_SE.last-name as l}{l}"`
	Personnummer string `fake:"{s.personnummer}"`
	Email        string `fake:"{slugify(s.first-name)}.{slugify(l)}@example.com"`
	Street       string `fake:"{/sv_SE.address as a}{a.street} {a.street-number}"`
	PostalCode   string `fake:"{a.postal-code}"`
	Locality     string `fake:"{a.locality}"`
}

func TestSignup(t *testing.T) {
	day := time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC)
	f, err := fejkdata.New(fejkdata.WithDataFS(svse.Modules()...), fejkdata.WithSeed(1), fejkdata.WithToday(day))
	if err != nil {
		t.Fatal(err)
	}
	var p Person
	if err := f.FakeStruct(&p); err != nil {
		t.Fatal(err)
	}
	// Sex is kvinna or man.
	// With seed 1, p is {Sex:kvinna First:Vira Last:Larsson Personnummer:501120-2388 Email:[email protected] Street:Kärrvägen 1 PostalCode:831 73 Locality:Östersund}
}
```

`WithSeed(1)` and `WithToday(day)` give the same person on every run of one version; another seed gives another.

### Python tests

`fejkdata.render` returns what the [CLI](#cli) prints for the same template, seed and day:

```sh
pip install fejkdata    # Python 3.11 or later, on Linux, macOS and Windows, amd64 and arm64
```

```python
import fejkdata

person = '{"format": "{/sv_SE.person as p}", "first": "{p.first}", "last": "{p.last}"}'
print(fejkdata.render(person, seed=1, today="2026-01-15", repeat=3, format="csv"), end="")
```

```text
first,last
Vinston,Larsson
Felix,Lind
Klara,Lassfolk
```

`fejkdata.paths()` returns every path the data offers, as `--list` prints them. The package carries
the CLI and all the shipped data, and doesn't depend on any other package.
[Its own README](python-package/README.md) lists the arguments and the error a refused call raises.

### JavaScript and TypeScript tests

`render` returns what the [CLI](#cli) prints for the same template, seed and day:

```sh
npm install @larvit/fejkdata    # Node 22.3 or later, Bun, Deno or a browser
```

```js
import { load } from "@larvit/fejkdata";

const fejkdata = await load();
const person = '{"format": "{/sv_SE.person as p}", "first": "{p.first}", "last": "{p.last}"}';
console.log(fejkdata.render(person, { seed: 1, today: "2026-01-15", repeat: 3, format: "csv" }).trimEnd());
```

```text
first,last
Vinston,Larsson
Felix,Lind
Klara,Lassfolk
```

The package is an ES module with TypeScript types, and doesn't depend on any other package.
`fake` draws one value of a path, `records` returns rows as objects, and `load` takes your own
data files. [The package's README](npm-package/README.md) lists the arguments and the error a
refused template throws. CI runs the package's tests on Node and Bun, and checks on Deno that it
loads and renders.

### Replacing real data with fakes

To replace the real values in existing text, such as a document holding real names, ids and URLs,
your program finds each real value and puts a fake of the same shape in its place.
fejkdata renders the fakes. Each part of the job:

- The same fake wherever one original recurs in a render: bind a pick to a name,
  `{/en_US.person as p}`, and read `{p}` each time ([Names](#names)).
- Free text, word by word: `{reword(text, /en_US.word)}` keeps its punctuation, digits,
  case and word lengths, where the text writes each `{` and `}` as `{{` and `}}`
  ([Transforms](#transforms)).
- A value of a given length: `{lower(n)}`, `{upper(n)}`, `{digits(n)}` or `{hex(n)}`
  ([Functions](#functions)).
- A v4 UUID: `{/misc.uuid}`, since `{uuid()}` draws a v7.
- An id of a fixed shape: literal text around a draw, such as `557058:{/misc.uuid}`
  ([Format string](#format-string)).
- A URL of a given form: `{/en_US.url}` draws a host and maybe a path, and the template
  adds the rest, such as `{/en_US.url}?{lower(4)}={digits(3)}`.
- A fake that doesn't hold its original: a `where` clause on its draw, such as
  `{hex(4) where not containing '7958'}`, which may read the original from a name. A clause
  filters the alphabet calls, such as `{hex(n)}` and `{uuid()}`, and a path whose values are fixed
  text ([Filters](#filters)).
- A longer word list than a locale's `word`: a category of your own ([Your own data](#your-own-data)).

```json
"{/en_US.person as p}{p} <{lower(6)}@example.com> signed as {p}, id 557058:{/misc.uuid}, {/en_US.url}?{lower(4)}={digits(3)}"
```

Renders e.g. `David Greer <[email protected]> signed as David Greer, id
557058:3bcf0fc3-f7b0-4d58-bf7f-88c29c39f316, https://blog.example.com?ojat=642`.

Your program keeps the rest of the job: giving one original the same fake across renders, and
keeping a fake from equalling or holding its original where no clause can filter it, as for
`{/en_US.person}`, `{reword()}` and `{/misc.uuid}`.

## CLI

```sh
echo '{/sv_SE.person}' | fejkdata                        # Sara Eriksson
echo '{/sv_SE.person.last}' | fejkdata                   # Eriksson
echo '{/sv_SE.person} hihi' | fejkdata                   # Sara Eriksson hihi
echo '{/sv_SE.address}' | fejkdata --seed 42             # the same address every run
echo '{/sv_SE.personnummer}' | fejkdata --seed 42 --today 2026-11-04   # the same number on any day
echo '{/sv_SE.word}' | fejkdata -n 3                     # nät, barn and sol, a line each
printf '%s' '{/sv_SE.word}' | fejkdata -n 3 --separator ', '   # nät, barn, sol
fejkdata --list                                          # every path the data offers
echo '{/misc.territory[SE].capital}' | fejkdata          # Stockholm — a table's row, selected by key or name
echo '{/geo.SE.locality[Lund].street}' | fejkdata        # Fjelievägen — a linked table, drawn inside the row
echo '{/sv_SE.word}' | fejkdata --data-path ./mydata     # layer a directory over the shipped data
fejkdata --no-shipped-data -d ./mydata --list            # only your data
echo '{"format":"name: {x}","x":["bosse","lina"]}' | fejkdata   # name: bosse or name: lina, with no trailing newline; see What stdin renders
fejkdata < template.txt                                  # a template kept in a file
fejkdata <<'EOF'                                         # born 2003-11-27 — a quoted heredoc passes ', $ and \ as written
born {date(1990-01-01,2010-12-31,'2006-01-02')}
EOF
```

fejkdata renders the template on its stdin: a format string, or a JSON object, array, string or `null`. Its `{…}` tokens reach the data by reference from the root,
`{/sv_SE.person.last}`, so shipped and `--data-path` categories are alike available,
and everything outside them prints as written. A reference names a category, or a field
inside one: each dot segment descends one level — folders, then the category (a JSON
file), then fields — and `[SE]` after a [table](#table) selects its row. `--list` prints
these paths; a template reads one as `{/path}`.

| Flag | |
|------|--|
| `-d`, `--data-path D` | a directory to layer over the shipped data; repeatable, the last wins a name clash |
| `--no-shipped-data` | load only the `--data-path` directories |
| `-s`, `--seed N` | same seed, date, data and versions: identical output (default: a random seed) |
| `--today DAY` | the date to treat as today, as `YYYY-MM-DD` from year 1000 on; ages in [`{born(…)}`](#functions), and so in `sv_SE.personnummer` and `sv_SE.person`, count from it, as does `today` in a [`{date(…)}`](#dates-around-today) bound (default: the system's date, so those draws change as days pass); give it beside `--seed` to repeat a run's output on a later day |
| `-n`, `--repeat N` | render the template N times (0 to 1048576), each an independent draw, streamed; `0` prints nothing, `[]` under `--format json`, or the header under `--format csv` or `tsv` |
| `--separator S` | between repeated renders (default empty); refused with a record `--format`, which has its own separators |
| `--format F` | `text` (default), `json`, `ndjson`, `csv`, `tsv`, `pgcopy` or `sql` — a record's columns, one record per row (json frames them as an array) |
| `--emit T=N` | write `N` records of the category `T`, as one of a run's [linked templates](#linked-templates) (repeatable); needs a record `--format`, and is refused beside `--table`, `--repeat` and a template on stdin |

Frequently Asked Questions

What is fejkdata?

fejkdata is a Miscellaneous library for the Go programming language. CLI and library that render fake test data from JSON templates, with related values that match

How do I install fejkdata?

Install fejkdata with the Go module system using `go get larvit/fejkdata`. Check the repository for the current installation instructions.

What category does fejkdata belong to?

fejkdata is listed under Miscellaneous, specifically Uncategorized.

← Back to Uncategorized