jsonobj

package module
v0.0.0-...-c223ae9 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2024 License: BSD-3-Clause Imports: 5 Imported by: 0

Documentation

Overview

Package jsonobj contains helpers for interacting with JSON objects.

Example (RetainRoundtrip)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/prashantv/pkg/jsonobj"
)

// Ensure Page is Retainable.
var _ any = jsonobj.MustRetainable(&Page{})

type Page struct {
	raw jsonobj.Retain

	Title string `json:"title"`
	Slug  string `json:"slug"`
}

func (p *Page) UnmarshalJSON(data []byte) error {
	return p.raw.FromJSON(data, p)
}

func (p Page) MarshalJSON() ([]byte, error) {
	return p.raw.ToJSON(p)
}

func main() {
	var p Page
	input := `{"title":"Contact Us","slug":"contact","icon":"email"}`
	if err := json.Unmarshal([]byte(input), &p); err != nil {
		log.Fatalf("Unmarshal failed: %v", err)
	}

	p.Slug = "contact-us" // update the slug value
	marshalled, err := json.Marshal(p)
	if err != nil {
		log.Fatalf("Marshal failed: %v", err)
	}

	// Note that output includes the updated "slug"
	// and retains the unknown "icon" field.
	fmt.Println(string(marshalled))
}
Output:
{"icon":"email","slug":"contact-us","title":"Contact Us"}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustRetainable

func MustRetainable(obj interface {
	json.Marshaler
	json.Unmarshaler
}) any

MustRetainable panics if the passed in object is not Retainable.

The return value is so it can be used in a var declaration such as:

var _ any = MustRetainable(&ObjType{})

func Retainable

func Retainable(obj interface {
	json.Marshaler
	json.Unmarshaler
}) (retErr error)

Retainable checks that the provided type is supported for Retain marshalling by checking that:

  • The type is a struct pointer (for `UnmarshalJSON` to work correctly).
  • The type has no duplicate JSON field names.
  • The type has no unsupported json tags.

Types

type Retain

type Retain struct {
	// contains filtered or unexported fields
}

Retain preserves unknown fields when marshalling JSON. It should be added as an unexported field in a struct, with UnmarshalJSON / MarshalJSON methods that call FromJSON and ToJSON.

func (*Retain) FromJSON

func (r *Retain) FromJSON(data []byte, obj any) error

FromJSON should be called from obj.UnmarshalJSON where obj is the struct for which unknown fields should be retained.

func (*Retain) ToJSON

func (r *Retain) ToJSON(obj any) ([]byte, error)

ToJSON should be called from obj.MarshalJSON where obj is the struct being marshalled with unknown fields (retained in FromJSON).

Jump to

Keyboard shortcuts

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