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"
)
encoding/json: Standard library package for JSON encoding and decoding.github.com/google/jsonschema-go/jsonschema: Provides JSON Schema validation capabilities.
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:
Marshaling
vinto JSON.Optionally validating the JSON against a provided
resolvedSchema.Unmarshaling the JSON into the target type
To.
Parameters
v From: The input value to convert.resolvedSchema *jsonschema.Resolved: An optional pointer to a resolved JSON Schema used to validate the JSON representation ofv. Ifnil, no validation occurs.
Returns
(To, error): Returns the converted value of typeTo, or an error if any step fails (marshaling, validation, unmarshaling).
Behavior and Implementation Details
Marshaling Input
The inputvis marshaled into JSON bytes (rawArgs). If marshaling fails, the function returns an error immediately.Optional Validation
IfresolvedSchemais non-nil, the JSON bytes are unmarshaled into a genericmap[string]anyto allow flexible validation. This is necessary because direct struct validation can fail to account for features likeomitemptyor custom marshal logic in Go structs.
TheresolvedSchema.Validate(m)method is called to validate the JSON data against the schema. Validation errors are returned immediately.Unmarshaling to Target Type
The JSON bytes are unmarshaled into a new variable of typeTo. If unmarshaling fails, an error is returned.Return
The converted, validated, and unmarshaled value is returned along with anilerror 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
The function uses generics (
[From, To any]) to allow conversion between any two types without loss of compile-time type safety.JSON serialization serves as an intermediate representation enabling conversion between arbitrary Go types that may not have direct conversion paths.
Schema validation is performed on a generic map representation of the JSON to properly handle optional fields and custom marshaling behaviors, addressing limitations in struct-based validation. This approach references jsonschema-go issue #23.
The zero value of the target type (
zero To) is returned on errors to comply with Go idiomatic error handling.
Interaction with Other System Components
This utility function depends on the
jsonschemapackage for JSON Schema validation, which is crucial for enforcing data integrity when converting between types.It is likely used in higher-level components that require safe transformations between data types, especially where input data must conform to specific JSON Schema constraints before further processing.
Can be integrated within systems handling dynamic data structures, such as APIs, data import/export modules, or configuration management tools.
This conversion utility complements other type handling and validation utilities within the project, potentially interacting with the Artifact Management or Agent Workflow Management subsystems where data transformations under schema constraints are essential.
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 |
|---|---|
| Generic function converting values between types via JSON serialization and optional schema validation. |
| Generic type parameters representing source and target types respectively. |
| Optional JSON Schema to validate JSON representation before conversion. |
Use of JSON marshaling | Enables flexible and type-agnostic conversion between Go types. |
Validation on | 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.