JGD-rs - JSON Generator Definition Rust Library
A powerful Rust library for generating realistic JSON data using declarative schema definitions. JGD (JSON Generator Definition) provides a flexible way to create fake data with complex relationships, cross-references, and customizable generation rules.
Features
- 🎯 Declarative Schema: Define data structure using JSON schemas
- 🌍 Multi-locale Support: Generate data in different languages (EN, FR_FR, DE_DE, IT_IT, PT_BR, JA_JP, AR_SA, CY_GB)
- 🔄 Cross-references: Link data between entities with automatic relationship management
- 🎲 Deterministic Generation: Use seeds for reproducible data generation
- 📊 Rich Data Types: Support for arrays, objects, numbers, booleans, and complex nested structures
- 🏭 Faker Integration: Built-in fake data generation using faker patterns
- ⚙️ Flexible Counts: Generate fixed or random counts of data
- 🔧 Optional Fields: Probability-based field generation
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Quick Start
Basic Usage with Library Functions
The simplest way to use jgd-rs is through the convenience functions:
use ;
use PathBuf;
// Generate from JSON string
let schema = r#"{
"$format": "jgd/v1",
"version": "1.0.0",
"root": {
"fields": {
"name": "${name.firstName}",
"email": "${internet.safeEmail}",
"age": {
"number": {
"min": 18,
"max": 65,
"integer": true
}
}
}
}
}"#;
let json_data = generate_jgd_from_str;
println!;
// Generate from file
let file_path = from;
let json_data = generate_jgd_from_file;
Advanced Usage with Jgd Struct
For more control, use the Jgd struct directly:
use Jgd;
let schema = r#"{
"$format": "jgd/v1",
"version": "1.0.0",
"seed": 42,
"defaultLocale": "EN",
"root": {
"fields": {
"id": "${ulid}",
"profile": {
"fields": {
"name": "${name.name}",
"email": "${internet.safeEmail}",
"location": "${address.cityName}, ${address.stateName}"
}
}
}
}
}"#;
// Parse schema
let jgd = from;
// Generate data
let result = jgd.generate;
Schema Modes
JGD supports two mutually exclusive generation modes:
Root Mode
Generate a single entity (object or array):
Entities Mode
Generate multiple named entities with relationships:
Schema Structure
Required Fields
$format: Schema format version (always "jgd/v1")version: User-defined schema version- Either
rootORentities(mutually exclusive)
Optional Fields
seed: Random seed for deterministic generationdefaultLocale: Locale for fake data (default: "EN")
Field Types
Primitive Values
Template Strings
Number Generation
Array Generation
Optional Fields
Cross-references
Nested Objects
Fake Data Generation
The library uses faker patterns to generate realistic data. All template strings use the ${category.method} format:
Supported Categories
Address
address.cityPrefix- City prefix (North, South, etc.)address.citySuffix- City suffix (town, ville, etc.)address.cityName- Full city nameaddress.countryName- Country nameaddress.countryCode- Country code (US, CA, etc.)address.streetSuffix- Street suffix (St, Ave, etc.)address.streetName- Street nameaddress.timeZone- Time zoneaddress.stateName- State nameaddress.stateAbbr- State abbreviationaddress.zipCode- ZIP codeaddress.postCode- Postal codeaddress.buildingNumber- Building numberaddress.latitude- Latitude coordinateaddress.longitude- Longitude coordinateaddress.geohash(precision)- Geohash with optional precision
Name
name.firstName- First namename.lastName- Last namename.title- Name title (Mr., Mrs., etc.)name.suffix- Name suffix (Jr., Sr., etc.)name.name- Full namename.nameWithTitle- Full name with title
Internet
internet.freeEmailProvider- Email provider (gmail.com, etc.)internet.domainSuffix- Domain suffix (.com, .org, etc.)internet.freeEmail- Free email addressinternet.safeEmail- Safe email addressinternet.username- Usernameinternet.password(length)- Password with optional lengthinternet.IPv4- IPv4 addressinternet.IPv6- IPv6 addressinternet.IP- IP address (v4 or v6)internet.MACAddress- MAC addressinternet.userAgent- User agent string
Company
company.companySuffix- Company suffix (Inc, LLC, etc.)company.companyName- Company namecompany.buzzword- Business buzzwordcompany.buzzwordMiddle- Middle buzzwordcompany.buzzwordTail- Tail buzzwordcompany.catchPhrase- Catch phrasecompany.bsVerb- Business verbcompany.bsAdj- Business adjectivecompany.bsNoun- Business nouncompany.bs- Business speakcompany.profession- Professioncompany.industry- Industry
Lorem
lorem.word- Single wordlorem.words(count)- Multiple wordslorem.sentence(min,max)- Sentence with word count rangelorem.sentences(count)- Multiple sentenceslorem.paragraph(min,max)- Paragraph with sentence count rangelorem.paragraphs(count)- Multiple paragraphs
Time & Date
chrono.time- Timechrono.date- Datechrono.dateTime- Date and timechrono.duration- Durationchrono.dateTimeBefore(date)- Date before specified datechrono.dateTimeAfter(date)- Date after specified datechrono.dateTimeBetween(start,end)- Date between two dates
Time Aliases (same as chrono.*):
time.time- Time (alias for chrono.time)time.date- Date (alias for chrono.date)time.dateTime- Date and time (alias for chrono.dateTime)time.duration- Duration (alias for chrono.duration)time.dateTimeBefore(date)- Date before specified date (alias for chrono.dateTimeBefore)time.dateTimeAfter(date)- Date after specified date (alias for chrono.dateTimeAfter)time.dateTimeBetween(start,end)- Date between two dates (alias for chrono.dateTimeBetween)
Numbers & Identifiers
number.digit- Single digitnumber.numberWithFormat(format)- Number with custom formatulid- ULID identifieruuid.v4- UUID v4
Colors
color.hexColor- Hex color (#ffffff)color.rgbColor- RGB colorcolor.rgbaColor- RGBA colorcolor.hslColor- HSL colorcolor.hslaColor- HSLA colorcolor.color- Color name
Phone & Contact
phone_number.phoneNumber- Phone numberphone_number.cellNumber- Cell phone number
Finance
creditcard.creditCardNumber- Credit card numberfinance.bic- Bank Identifier Codefinance.isin- International Securities Identification Numbercurrency.currencyCode- Currency code (USD, EUR, etc.)currency.currencyName- Currency namecurrency.currencySymbol- Currency symbol
Filesystem
filesystem.filePath- File pathfilesystem.fileName- File namefilesystem.fileExtension- File extensionfilesystem.dirPath- Directory pathfilesystem.mimeType- MIME typefilesystem.semver- Semantic versionfilesystem.semverStable- Stable semantic versionfilesystem.semverUnstable- Unstable semantic version
Markdown
markdown.italicWord- Italic formatted wordmarkdown.boldWord- Bold formatted wordmarkdown.link- Markdown linkmarkdown.bulletPoints- Bullet point listmarkdown.listItems- List itemsmarkdown.blockQuoteSingleLine- Single line block quotemarkdown.blockQuoteMultiLine- Multi-line block quotemarkdown.code- Code block
Administrative
administrative.healthInsuranceCode- Health insurance code
Automotive
automotive.licencePlate- License plate number
Other Categories
barcode.isbn- ISBN barcodebarcode.isbn10- ISBN-10barcode.isbn13- ISBN-13boolean.boolean(ratio)- Boolean with optional true ratiojob.seniority- Job seniority leveljob.field- Job fieldjob.position- Job positionjob.title- Job titlehttp.rfcStatusCode- HTTP status codehttp.validStatusCode- Valid HTTP status code
Method Arguments
Many faker methods accept arguments:
Localization
Set the defaultLocale field to generate locale-specific data:
Supported Locales:
EN- English (default)FR_FR- French (France)DE_DE- German (Germany)IT_IT- Italian (Italy)PT_BR- Portuguese (Brazil)JA_JP- Japanese (Japan)AR_SA- Arabic (Saudi Arabia)CY_GB- Welsh (Great Britain)
Count Specifications
Control how many items to generate:
Fixed Count
Range Count
Default Count
If no count is specified, generates a single item.
Cross-References
Link data between entities using the ref field:
The ref field format is "entityName.fieldName". The library will randomly select from the generated entity data.
Deterministic Generation
Use seeds for reproducible output:
let schema_with_seed = r#"{
"$format": "jgd/v1",
"version": "1.0.0",
"seed": 42,
"root": {
"fields": {
"random_number": {
"number": {
"min": 1,
"max": 100,
"integer": true
}
}
}
}
}"#;
let jgd1 = from;
let jgd2 = from;
let result1 = jgd1.generate;
let result2 = jgd2.generate;
// result1 == result2 (same seed produces identical output)
API Reference
Library Functions
generate_jgd_from_str(schema: &str) -> Value
Generate JSON data from a schema string.
generate_jgd_from_file(path: &PathBuf) -> Value
Generate JSON data from a schema file.
Jgd Struct
Jgd::from(schema: &str) -> Jgd
Parse a schema from a string.
Jgd::from(schema: String) -> Jgd
Parse a schema from an owned string.
Jgd::from(schema: Value) -> Jgd
Parse a schema from a JSON value.
Jgd::from_file(path: &PathBuf) -> Jgd
Load a schema from a file.
jgd.generate() -> Value
Generate JSON data according to the schema.
jgd.create_config() -> GeneratorConfig
Create a generator configuration from the schema settings.
Schema Fields
format: String
Schema format identifier (e.g., "jgd/v1").
version: String
User-defined schema version.
seed: Option<u64>
Optional random seed for deterministic generation.
default_locale: String
Locale for fake data generation (default: "EN").
entities: Option<IndexMap<String, Entity>>
Named entity definitions for entities mode.
root: Option<Entity>
Root entity definition for root mode.
Examples
Simple User Profile
Blog System with Relationships
E-commerce Product Catalog
Error Handling
The library will panic on invalid schemas. Ensure your schemas:
- Include required fields (
$format,version) - Have either
rootORentities(not both) - Use valid JSON syntax
- Reference existing entities in cross-references
- Use supported faker patterns
Performance
- Use seeds for deterministic generation when testing
- Consider count ranges for more realistic data distribution
- Cross-references are resolved efficiently using internal caching
- Large datasets are generated lazily where possible
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.