convert.go

Overview

The convert.go file in the typeutil package provides a utility function to convert values between arbitrary Go types using JSON serialization and deserialization. It leverages JSON marshaling to transform an input value of one type into a target type by first encoding it to JSON and then decoding it back. Additionally, this conversion process optionally validates the intermediate JSON representation against a provided JSON Schema, ensuring that the data adheres to expected structural constraints during conversion.

This approach abstracts away manual type conversions and enables safe, schema-validated transformations between complex or disparate Go data structures.

Detailed Explanation

Package

package typeutil

The package typeutil is a collection of utility functions for handling Go types, focusing on conversions and type-related operations.


Import Dependencies

import (
	"encoding/json"
	"github.com/google/jsonschema-go/jsonschema"
)

Function: ConvertToWithJSONSchema

func ConvertToWithJSONSchema[From, To any](v From, resolvedSchema *jsonschema.Resolved) (To, error)

Purpose

Converts a value v of type From to another type To by:

  1. Marshaling v into JSON.

  2. Optionally validating the JSON against a provided resolvedSchema.

  3. Unmarshaling the JSON into the target type To.

Parameters

Returns

Behavior and Implementation Details

  1. Marshaling Input
    The input v is marshaled into JSON bytes (rawArgs). If marshaling fails, the function returns an error immediately.

  2. Optional Validation
    If resolvedSchema is non-nil, the JSON bytes are unmarshaled into a generic map[string]any to allow flexible validation. This is necessary because direct struct validation can fail to account for features like omitempty or custom marshal logic in Go structs.
    The resolvedSchema.Validate(m) method is called to validate the JSON data against the schema. Validation errors are returned immediately.

  3. Unmarshaling to Target Type
    The JSON bytes are unmarshaled into a new variable of type To. If unmarshaling fails, an error is returned.

  4. Return
    The converted, validated, and unmarshaled value is returned along with a nil error on success.

Usage Example

type Source struct {
	Name string
	Age  int
}

type Target struct {
	Name string
	Age  int
}

var schema *jsonschema.Resolved = ... // Assume a JSON Schema is resolved here

source := Source{Name: "Alice", Age: 30}
target, err := ConvertToWithJSONSchema[Source, Target](source, schema)
if err != nil {
    // Handle error: could be marshaling, validation or unmarshaling failure
}
// Use target of type Target

Important Implementation Details


Interaction with Other System Components


Diagram: Function Workflow

flowchart TD
A["Input value v (type From)"]
B[Marshal v to JSON bytes]
C{Is resolvedSchema provided?}
D["Unmarshal JSON to map[string"]any]
E[Validate map against resolvedSchema]
F[Unmarshal JSON to type To]
G["Return converted value (type To)"]
H[Return error]
A --> B
B -- marshaling error --> H
B --> C
C -- No --> F
C -- Yes --> D
D -- unmarshal error --> H
D --> E
E -- validation error --> H
E --> F
F -- unmarshal error --> H
F --> G

Summary of Key Elements

Element

Description

ConvertToWithJSONSchema

Generic function converting values between types via JSON serialization and optional schema validation.

From and To

Generic type parameters representing source and target types respectively.

resolvedSchema

Optional JSON Schema to validate JSON representation before conversion.

Use of JSON marshaling

Enables flexible and type-agnostic conversion between Go types.

Validation on map[string]any

Ensures proper schema validation accounting for omitempty and custom marshaling.


This file provides a critical utility for safe and validated type conversion using JSON as an intermediate format, ensuring data correctness and type compatibility within the broader system. For more on JSON Schema validation and Go type handling, see related topics on JSON Schema integration and type utilities.