dataformat

package
v0.111.5 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 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.

Documentation

Overview

Package dataformat provides bidirectional conversion primitives between the structured data formats commonly seen across the fleet: JSON, CSV, XML, YAML and TOML.

The package exposes a small, format-agnostic surface:

DetectFormat(b []byte) (Format, error)   // best-effort sniff
Decode(f Format, b []byte) (any, error)  // bytes  -> Go value
Encode(f Format, v any) ([]byte, error)  // Go value -> bytes
Convert(from, to Format, b []byte) ([]byte, error)

Decode always yields a "generic" Go value built from map[string]any, []any and scalars (string/float64/bool/nil), so a value decoded from one format can be re-encoded into any other without a concrete struct.

Lossy edges

Not every format pair is total. The conversions are intentionally explicit about where information is lost or where a shape is required:

  • CSV is tabular. Encoding to CSV requires either an array of objects with consistent (string-keyed) fields, or an array of arrays. Decoding CSV infers column names from the header row and produces an []any of map[string]any rows; every cell value is a string (CSV has no type system). Converting a non-tabular value to CSV returns ErrNotTabular.

  • XML has no native arrays or a typed scalar model, and it distinguishes attributes from child elements. Decode unmarshals XML into a map[string]any tree where attributes are folded in with a "-" prefix and character data is stored under "#text"; repeated sibling elements become an []any. Round-tripping arbitrary JSON/YAML/TOML through XML is therefore lossy: there is no canonical way to render an array or a top-level scalar as XML. Encoding a value XML cannot faithfully represent returns ErrUnsupportedShape.

  • TOML requires a table (map) at the top level; it cannot encode a bare array or scalar as a document. Encoding such a value returns ErrUnsupportedShape.

All shape/parse failures are reported through typed errors (see the Err* sentinels and the *Error types) so callers can branch with errors.Is / errors.As.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnknownFormat is returned by ParseFormat for an unrecognized name.
	ErrUnknownFormat = errors.New("dataformat: unknown format")
	// ErrDetectFailed is returned by DetectFormat when no format matches.
	ErrDetectFailed = errors.New("dataformat: could not detect format")
	// ErrNotTabular is returned when a value cannot be shaped into CSV rows.
	ErrNotTabular = errors.New("dataformat: value is not tabular")
	// ErrUnsupportedShape is returned when a value cannot be represented in
	// the target format (e.g. a bare array/scalar to TOML or XML).
	ErrUnsupportedShape = errors.New("dataformat: value shape unsupported by target format")
	// ErrEmptyInput is returned when decoding empty input.
	ErrEmptyInput = errors.New("dataformat: empty input")
)

Sentinel errors. Use errors.Is to test for them.

Functions

func Convert

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

Convert decodes b from the "from" format and re-encodes it as "to". It is a thin composition of Decode and Encode; lossy edges (see package docs) apply to the encode step.

func Decode

func Decode(f Format, b []byte) (any, error)

Decode parses b in format f into a generic Go value composed of map[string]any, []any and scalars, suitable for re-encoding into any other format. Parse failures are returned as *DecodeError.

func Encode

func Encode(f Format, v any) ([]byte, error)

Encode serializes v into format f. Shape mismatches (e.g. a bare array to TOML) are returned as *EncodeError wrapping ErrUnsupportedShape or ErrNotTabular.

Types

type DecodeError

type DecodeError struct {
	Format Format
	Err    error
}

DecodeError wraps an underlying decode/parse failure with the format.

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type EncodeError

type EncodeError struct {
	Format Format
	Err    error
}

EncodeError wraps an underlying encode failure with the format.

func (*EncodeError) Error

func (e *EncodeError) Error() string

func (*EncodeError) Unwrap

func (e *EncodeError) Unwrap() error

type Format

type Format int

Format identifies a structured data serialization.

const (
	// JSON is RFC 8259 JSON.
	JSON Format = iota
	// CSV is RFC 4180 comma-separated values with a header row.
	CSV
	// XML is XML 1.0.
	XML
	// YAML is YAML 1.1 (via go.yaml.in/yaml/v2).
	YAML
	// TOML is TOML v1.0.0 (via github.com/BurntSushi/toml).
	TOML
)

func DetectFormat

func DetectFormat(b []byte) (Format, error)

DetectFormat makes a best-effort guess at the format of b. It is a heuristic sniffer, not a validator: the result is the most plausible format, and a follow-up Decode is the authoritative check. Detection order is chosen so that the most structurally distinctive formats win.

func ParseFormat

func ParseFormat(s string) (Format, error)

ParseFormat maps a (case-insensitive) name to a Format. It accepts the canonical names plus a few common aliases ("yml", "text/csv", ...).

func (Format) String

func (f Format) String() string

String returns the canonical lower-case name of the format.

Jump to

Keyboard shortcuts

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