/structil

Dynamic struct utilities for generic data decoding (for JSON and more) in Go

Primary LanguageGoMIT LicenseMIT

structil PkgGoDev

Workflow Status Go Report Card Codecov MIT License

struct + util = structil, for runtime and dynamic environment in Go.

Why?

I'd like to ...

  • conveniently dive into the specific field in nested struct
  • simply verify if a field with the specified name and type exists in object
  • conveniently handle known and unknown formatted JSON/YAML
  • etc
*** JSON and YAML format is known or unknown ***


JSON →↓        →→ (known case) struct  →→→→→→→→→↓→→ (use struct directly)
      ↓        ↑                                ↓
      ↓→→ map →→→ (unknown case) DynamicStruct →→→ Getter, Finder
      ↑
YAML →↑

Please see my medium post as well.

Examples

Finder

We can access usefully nested struct fields using field name string.

See example code

With config file? use FinderKeys

We can create a Finder from the configuration file that have some finding target keys. We support some file formats of configuration file such as yaml, json, toml and more.

See example code

Thanks for the awesome configuration management library spf13/viper.

Getter

We can access a struct using field name string, like map.

See example code

MapGet method

MapGet method provides the Map collection function for slice of struct

See example code

DynamicStruct

We can create the dynamic and runtime struct.

See example code

JSON unmershal with DynamicStruct

A decoding example from JSON to DynamicStruct with StructTag using json.Unmarshal([]byte) as follows. This example works correctly not only JSON but also YAML, TOML and more.

See example code

GenericDecoder

A decoding example from unknown format JSON to interface of DynamicStruct with JSONGenericDecoder.Decode as follows.

See example code

Benchmark

See this file

It's the latest benchmark result that is executed on GitHub Actions runner instance.