convert

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 8 Imported by: 0

README

common/convert

Type-safe conversion utilities and format interconversion (JSON / TOML / YAML).

Type Conversion

Convert any value to the target type with clear error messages:

import "github.com/LingByte/ling-base/common/convert"

n, err   := convert.ToInt("42")         // 42, nil
f, err   := convert.ToFloat64("3.14")   // 3.14, nil
b, err   := convert.ToBool("yes")       // true, nil
s, err   := convert.ToString(42)        // "42", nil
d, err   := convert.ToDuration("5s")    // 5 * time.Second, nil

// Slice conversion
ints, err   := convert.ToSlice[int]([]any{1, 2, 3})       // []int{1,2,3}
strs, err   := convert.ToSliceString([]any{"a", "b"})     // []string{"a","b"}

// Map conversion (YAML often returns map[any]any)
m, err := convert.ToMapStringAny(map[any]any{"key": "val"}) // map[string]any{"key":"val"}
Supported types
Function From
ToInt int, uint, float, string, bool, json.Number
ToInt64 same as ToInt + large floats
ToUint same as ToInt (rejects negative)
ToFloat64 float, int, string, bool, json.Number
ToBool bool, string (true/false/1/0/yes/no/on/off), int
ToString string, bool, all numerics, []byte, fmt.Stringer, json.Number, JSON fallback
ToDuration time.Duration, string ("5s"), int (nanoseconds)
ToSlice[T] []T, []any (element-wise), single value → []T
ToMapStringAny map[any]any, map[string]any

Format Interconversion

Convert between JSON, TOML, and YAML:

// Direct conversion functions
yamlBytes, err := convert.FromJSONToYAML(jsonBytes)
jsonBytes, err := convert.FromYAMLToJSON(yamlBytes)
tomlBytes, err := convert.FromJSONToTOML(jsonBytes)
jsonBytes, err := convert.FromTOMLToJSON(tomlBytes)
tomlBytes, err := convert.FromYAMLToTOML(yamlBytes)
yamlBytes, err := convert.FromTOMLToYAML(tomlBytes)

// Generic Convert (any → any)
result, err := convert.Convert(convert.FormatJSON, convert.FormatYAML, data)

// Marshal / Unmarshal with explicit format
bytes, err := convert.Marshal(convert.FormatTOML, myStruct)
err = convert.Unmarshal(convert.FormatYAML, data, &myStruct)

// Struct-level helpers
jsonBytes, err := convert.StructToJSON(myStruct)
err = convert.YAMLToStruct(yamlBytes, &myStruct)
TOML note

TOML requires a map or struct at the top level. If you convert a JSON array or scalar to TOML, it is automatically wrapped under a "data" key.

Deep Copy / Clone

// Type-safe deep copy via JSON round-trip
copied, err := convert.Clone(original)

// Generic deep copy (returns any)
copied, err := convert.CopyJSON(original)

// Deep copy that returns zero on error (no error return)
copied := convert.DeepCopy(original)

Map Utilities

// Convert any map to map[string]string
m, err := convert.ToMapStringString(map[string]int{"count": 42})
// → map[string]string{"count": "42"}

// Convert any map to map[string]int
m, err := convert.ToMapStringInt(map[string]string{"count": "42"})
// → map[string]int{"count": 42}

JSON Convenience

// Parse JSON to map
m, err := convert.JSONToMap([]byte(`{"key":"value"}`))

// Parse JSON to slice
s, err := convert.JSONToSlice([]byte(`[1,2,3]`))

// Panic-on-error variants for static data
b := convert.MustMarshal(convert.FormatJSON, data)
convert.MustUnmarshal(convert.FormatJSON, data, &result)

License

MIT

Documentation

Overview

Package convert provides type-safe conversion utilities and format interconversion (JSON / TOML / YAML).

Type Conversion

The ToXxx family of functions convert any value to the target type, returning a zero value and/or error on failure:

ToInt("42")           → 42, nil
ToInt("abc")          → 0, error
ToString(42)          → "42", nil
ToFloat64("3.14")     → 3.14, nil
ToBool("true")        → true, nil
ToSlice[int]([]any{1,2,3}) → []int{1,2,3}, nil

Format Interconversion

Convert between JSON, TOML, and YAML representations:

json, err := convert.FromYAMLToJSON(yamlBytes)
toml, err := convert.FromJSONToTOML(jsonBytes)
yaml, err := convert.FromTOMLToYAML(tomlBytes)

All interconversion functions decode the source into a generic map[string]any (or []any for arrays) and re-encode to the target format.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clone

func Clone[T any](v T) (T, error)

Clone is a type-safe deep copy that returns the same type as input. Uses JSON round-trip, so unexported fields are not preserved.

func Convert

func Convert(from, to Format, data []byte) ([]byte, error)

Convert converts data from one format to another. The source is decoded into a generic any and re-encoded to the target format.

func CopyJSON

func CopyJSON(v any) (any, error)

CopyJSON creates a deep copy of v via JSON round-trip into a new value of the same type. Returns an error if marshaling or unmarshaling fails.

func DeepCopy

func DeepCopy[T any](v T) T

DeepCopy creates a deep copy of v via JSON round-trip. Returns nil if the value cannot be marshaled. This is suitable for structs, maps, slices, and primitives. Unexported fields are NOT copied (JSON does not see them).

func FromJSONToTOML

func FromJSONToTOML(data []byte) ([]byte, error)

FromJSONToTOML converts JSON bytes to TOML.

func FromJSONToYAML

func FromJSONToYAML(data []byte) ([]byte, error)

FromJSONToYAML converts JSON bytes to YAML.

func FromTOMLToJSON

func FromTOMLToJSON(data []byte) ([]byte, error)

FromTOMLToJSON converts TOML bytes to JSON.

func FromTOMLToYAML

func FromTOMLToYAML(data []byte) ([]byte, error)

FromTOMLToYAML converts TOML bytes to YAML.

func FromYAMLToJSON

func FromYAMLToJSON(data []byte) ([]byte, error)

FromYAMLToJSON converts YAML bytes to JSON.

func FromYAMLToTOML

func FromYAMLToTOML(data []byte) ([]byte, error)

FromYAMLToTOML converts YAML bytes to TOML.

func JSONToMap

func JSONToMap(data []byte) (map[string]any, error)

JSONToMap converts JSON bytes to map[string]any.

func JSONToSlice

func JSONToSlice(data []byte) ([]any, error)

JSONToSlice converts JSON bytes to []any.

func JSONToStruct

func JSONToStruct(data []byte, v any) error

JSONToStruct decodes JSON bytes into a struct.

func Marshal

func Marshal(format Format, v any) ([]byte, error)

Marshal encodes v to the specified format.

func MustMarshal

func MustMarshal(format Format, v any) []byte

MustMarshal is like Marshal but panics on error. Use only for static data in tests or initialization.

func MustUnmarshal

func MustUnmarshal(format Format, data []byte, v any)

MustUnmarshal is like Unmarshal but panics on error.

func StructToJSON

func StructToJSON(v any) ([]byte, error)

StructToJSON encodes a struct to JSON bytes.

func StructToTOML

func StructToTOML(v any) ([]byte, error)

StructToTOML encodes a struct to TOML bytes.

func StructToYAML

func StructToYAML(v any) ([]byte, error)

StructToYAML encodes a struct to YAML bytes.

func TOMLToStruct

func TOMLToStruct(data []byte, v any) error

TOMLToStruct decodes TOML bytes into a struct.

func ToBool

func ToBool(v any) (bool, error)

ToBool converts any value to bool. Recognizes: bool, string ("true"/"false"/"1"/"0"/"yes"/"no"/"on"/"off"), int (non-zero = true).

func ToDuration

func ToDuration(v any) (time.Duration, error)

ToDuration converts any value to time.Duration. Accepts time.Duration, string (e.g. "5s", "100ms"), and numeric types (interpreted as nanoseconds).

func ToFloat64

func ToFloat64(v any) (float64, error)

ToFloat64 converts any value to float64.

func ToInt

func ToInt(v any) (int, error)

ToInt converts any value to int. Supports int variants, float variants, string (parsed), bool (1/0), and json.Number.

func ToInt64

func ToInt64(v any) (int64, error)

ToInt64 converts any value to int64.

func ToMapStringAny

func ToMapStringAny(v any) (map[string]any, error)

ToMapStringAny converts a map[any]any (common from YAML decoding) to map[string]any. Keys that are not strings are converted via fmt.Sprint.

func ToMapStringInt

func ToMapStringInt(v any) (map[string]int, error)

ToMapStringInt converts any map to map[string]int. Values are converted via ToInt. Keys are converted via ToString.

func ToMapStringString

func ToMapStringString(v any) (map[string]string, error)

ToMapStringString converts any map to map[string]string. Values are converted via ToString. Keys are converted via ToString.

func ToSlice

func ToSlice[T any](v any) ([]T, error)

ToSlice converts any value to a typed slice. If v is already a slice of T, it is returned directly. If v is a []any, each element is converted to T. If v is a single value, a slice containing that one value is returned.

func ToSliceInt

func ToSliceInt(v any) ([]int, error)

ToSliceInt converts any value to []int.

func ToSliceString

func ToSliceString(v any) ([]string, error)

ToSliceString converts any value to []string.

func ToString

func ToString(v any) (string, error)

ToString converts any value to string. Numbers are formatted, bool becomes "true"/"false", nil becomes "".

func ToUint

func ToUint(v any) (uint, error)

ToUint converts any value to uint.

func Unmarshal

func Unmarshal(format Format, data []byte, v any) error

Unmarshal decodes data in the specified format into v.

func YAMLToStruct

func YAMLToStruct(data []byte, v any) error

YAMLToStruct decodes YAML bytes into a struct.

Types

type Format

type Format string

Format represents a serialization format.

const (
	FormatJSON Format = "json"
	FormatYAML Format = "yaml"
	FormatTOML Format = "toml"
)

Jump to

Keyboard shortcuts

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