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.
Click to show internal directories.
Click to hide internal directories.