pjson

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2023 License: MIT Imports: 5 Imported by: 2 modules, 2 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.

README

pjson

Go Reference Go Coverage

Help to easily JSON marshal / unmarshal tagged unions in go

A tagged union / discriminating type is, for instance with the following JSON:

[
    { "type": "a", "a_name": "AName", "a_foo": "FOO" },
    { "type": "b", "b_name": "BName", "b_goo": "GOO" }
]

The type field denotes which type the object is. So many object share a common discriminating field. In some languages this is supported, but not in go.

Pjson gives us a helper pjson.Tagged type to create these pseudo tagged unions that can be automatically serialized and deserialized to and from JSON.

Usage

package readme

import (
	"encoding/json"
	"fmt"
	"reflect"
	
	"github.com/byrnedo/pjson"
)

type Foo struct {
	A string `json:"a"`
}

// set it's tag value
func (a Foo) Variant() string {
	return "foo"
}

type Bar struct {
	B string `json:"b"`
}

func (b Bar) Variant() string {
	return "bar"
}

// specify the union
type FooBarUnion struct{}

func (u FooBarUnion) Field() string { return "type" }

func (u FooBarUnion) Variants() []pjson.Variant {
	return []pjson.Variant{
		Foo{}, Bar{},
	}
}

func ExampleReadme() {
	// now that we have our types we can use OneOf
	o := pjson.Tagged[FooBarUnion]{}

	bytes := []byte(`{"type": "foo", "a": "AAAA"}`)

	err := json.Unmarshal(bytes, &o)
	if err != nil {
		panic(err)
	}

	fmt.Println(reflect.TypeOf(o.Value), o.Value)

	bytes, _ = json.Marshal(o)
	fmt.Println(string(bytes))

	// Output: *pjson_test.Foo &{AAAA}
	// {"a":"AAAA","type":"foo"}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Discriminator added in v1.0.0

type Discriminator interface {
	Field() string
	Variants() []Variant
}

type Tagged added in v1.0.0

type Tagged[T Discriminator] struct {
	Value Variant
	// contains filtered or unexported fields
}

func (Tagged[T]) MarshalJSON added in v1.0.0

func (o Tagged[T]) MarshalJSON() ([]byte, error)

func (*Tagged[T]) UnmarshalJSON added in v1.0.0

func (o *Tagged[T]) UnmarshalJSON(bytes []byte) error

type Variant

type Variant interface {
	Variant() string
}

Jump to

Keyboard shortcuts

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