dynamic-defaults

command
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Dynamic Default Values Example

Demonstrates using dynamic functions to generate default values during JSON unmarshaling.

Usage

go run dynamic_defaults.go

Key Features

  • Custom Functions: Register functions like uuid() and now() for dynamic defaults
  • Safe Execution: Unregistered functions fall back to literal values
  • Schema Integration: Define function calls directly in JSON schema default fields

Complete Example

package main

import (
    "uuid"

    jsonschema "github.com/ad3n/jsonschema"
)

func main() {
    // 1. Create compiler and register functions
    compiler := jsonschema.NewCompiler()
    compiler.RegisterDefaultFunc("now", jsonschema.DefaultNowFunc)
    compiler.RegisterDefaultFunc("uuid", func(args ...any) (any, error) {
        return uuid.New().String(), nil
    })

    // 2. Define schema with dynamic defaults
    schemaJSON := `{
        "type": "object",
        "properties": {
            "id": {"default": "uuid()"},
            "createdAt": {"default": "now()"},
            "status": {"default": "active"}
        }
    }`

    // 3. Compile schema
    schema, _ := compiler.Compile([]byte(schemaJSON))

    // 4. Unmarshal with partial input
    input := map[string]interface{}{"status": "pending"}
    
    var result map[string]interface{}
    schema.Unmarshal(&result, input)
    
    // result will contain:
    // {
    //   "id": "3ace637a-515a-4328-a614-b3deb58d410d",
    //   "createdAt": "2025-06-05T01:05:22+08:00", 
    //   "status": "pending"
    // }
}

Documentation

Overview

Package main demonstrates dynamic default value generation with the jsonschema library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL