Skip to main content

Field

Enum Field 

Source
pub enum Field {
    Array {
        array: ArraySpec,
    },
    Entity(Entity),
    Number {
        number: NumberSpec,
    },
    Optional {
        optional: OptionalSpec,
    },
    Ref {
        ref: String,
    },
    Str(String),
    Bool(bool),
    I64(i64),
    F64(f64),
    Null,
}
Expand description

A field specification that can generate any JSON value type.

Fields are the fundamental building blocks in JGD schemas. Each field variant corresponds to a different type of value generation strategy. The enum uses #[serde(untagged)] to support flexible JSON deserialization where the structure determines the variant.

§Variants

§Complex Types

  • Array: Generates arrays with configurable element types and counts
  • Entity: Generates nested objects with multiple fields
  • Optional: Conditionally generates values based on probability

§Dynamic Types

  • Ref: References values from other generated entities
  • Str: Template strings with placeholder substitution support

§Primitive Types

  • Number: Generates numbers within specified ranges
  • Bool: Static boolean values
  • I64: Static 64-bit integer values
  • F64: Static 64-bit floating-point values
  • Null: JSON null values

§JGD Schema Examples

{
  "name": "John Doe",                          // Field::Str
  "age": { "number": { "min": 18, "max": 65 } }, // Field::Number
  "active": true,                              // Field::Bool
  "score": 95.5,                              // Field::F64
  "id": 12345,                                // Field::I64
  "metadata": null,                           // Field::Null
  "email": "${internet.email}",               // Field::Str with template
  "user_id": { "ref": "users.id" },          // Field::Ref
  "tags": {                                   // Field::Array
    "array": {
      "count": 3,
      "of": "${lorem.word}"
    }
  },
  "profile": {                                // Field::Optional
    "optional": {
      "prob": 0.8,
      "of": { "bio": "${lorem.sentence}" }
    }
  }
}

§Deserialization

The #[serde(untagged)] attribute allows automatic variant detection:

  • Objects with "array" key → Field::Array
  • Objects with "number" key → Field::Number
  • Objects with "optional" key → Field::Optional
  • Objects with "ref" key → Field::Ref
  • Plain strings → Field::Str
  • Plain numbers → Field::I64 or Field::F64
  • Plain booleans → Field::Bool
  • nullField::Null

Variants§

§

Array

Array field that generates JSON arrays.

Wraps an ArraySpec that defines the element type and count for array generation. Arrays can contain any field type as elements and support dynamic sizing.

Fields

§

Entity(Entity)

Entity field that generates nested JSON objects.

Embeds a complete Entity specification for generating complex nested structures. Entities can contain multiple fields and support uniqueness constraints.

§

Number

Number field that generates numeric values within ranges.

Wraps a NumberSpec that defines the range and type (integer/float) for number generation. Supports both discrete integer ranges and continuous floating-point ranges.

Fields

§number: NumberSpec
§

Optional

Optional field that conditionally generates values.

Wraps an OptionalSpec that defines probability-based value generation. Can generate the specified field or null based on the configured probability.

Fields

§optional: OptionalSpec
§

Ref

Reference field that links to other generated entities.

Contains a dot-notation path string for accessing values from previously generated entities. Enables cross-referencing and relational data generation.

Fields

§

Str(String)

String field with template support.

Can be a literal string or contain ${...} placeholders for dynamic content generation. Supports faker function calls and cross-references to other entities.

§

Bool(bool)

Static boolean field.

Generates a fixed boolean value without any dynamic behavior.

§

I64(i64)

Static 64-bit integer field.

Generates a fixed integer value without any dynamic behavior.

§

F64(f64)

Static 64-bit floating-point field.

Generates a fixed floating-point value without any dynamic behavior.

§

Null

Null field.

Always generates a JSON null value.

Trait Implementations§

Source§

impl Clone for Field

Source§

fn clone(&self) -> Field

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Field

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Field

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl JsonGenerator for Field

Source§

fn generate( &self, config: &mut GeneratorConfig, local_config: Option<&mut LocalConfig>, ) -> Result<Value, JgdGeneratorError>

Generates a JSON value based on the field type.

This method dispatches to the appropriate generation logic for each field variant. It handles all supported field types and ensures proper JSON value generation according to the JGD specification.

§Parameters
  • config: Mutable reference to generator configuration for accessing state and utilities
§Returns
  • serde_json::Value: The generated JSON value appropriate for the field type
§Generation Behavior
  • Array: Delegates to ArraySpec::generate() for array creation
  • Entity: Delegates to Entity::generate() for object creation
  • Number: Delegates to NumberSpec::generate() for numeric value generation
  • Optional: Delegates to OptionalSpec::generate() for probability-based generation
  • Ref: Resolves cross-references using generate_for_ref()
  • Str: Processes template strings with placeholder replacement
  • Bool/I64/F64/Null: Direct conversion to corresponding JSON values
§Template Processing

String fields undergo template processing to replace ${...} placeholders:

  • Faker calls: "${name.firstName}""John"
  • Cross-references: "${users.id}""12345"
  • Function calls: "${lorem.words(3)}""lorem ipsum dolor"
§Examples
let field = Field::Str("Hello ${name.firstName}!".to_string());
let result = field.generate(&mut config);
// Result: Value::String("Hello John!")

let number_field = Field::Number {
    number: NumberSpec::new_integer(1.0, 100.0)
};
let result = number_field.generate(&mut config);
// Result: Value::Number(42)

Auto Trait Implementations§

§

impl Freeze for Field

§

impl RefUnwindSafe for Field

§

impl Send for Field

§

impl Sync for Field

§

impl Unpin for Field

§

impl UnsafeUnpin for Field

§

impl UnwindSafe for Field

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: Rng + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,