jsonutil

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 6 Imported by: 0

README

go-jsonutil

Go Reference

JSON Utilities for Go-lang encoding/json package.

Ordered JSON object.

MarshalEntries / UnmarshalEntries

Utility function to marshal / unmarshal JSON objects into slices in the same order.

Example
// IntEntry represents integer with key.
type IntEntry struct {
	Key string
	Int int
}

// IntEntries is the slices of IntEntry.
type IntEntries []*IntEntry

// UnmarshalJSON implements `json.Unmarshaler` interface.
func (ls *IntEntries) UnmarshalJSON(bs []byte) error {
	return jsonutil.UnmarshalEntries(bs, func(key string, data []byte) error {
		entry := &IntEntry{
			Key: key,
		}
		*ls = append(*ls, entry)
		return json.Unmarshal(data, &entry.Int)
	})
}

// MarshalJSON implements `json.Marshaler` interface.
func (ls IntEntries) MarshalJSON() ([]byte, error) {
	return jsonutil.MarshalEntries(len(ls), func(i int) *jsonutil.Entry {
		return &jsonutil.Entry{
			Key:   ls[i].Key,
			Value: ls[i].Int,
		}
	})
}

License

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	EmptyArray  = RawMessage(`[]`)
	EmptyObject = RawMessage(`{}`)
	True        = RawMessage(`true`)
	False       = RawMessage(`false`)
	Null        = RawMessage(`null`)
)

Useful JSON raw messages.

Functions

func MarshalEntries

func MarshalEntries(length int, resolveEntry func(i int) *Entry) ([]byte, error)

MarshalEntries is a utility function for

e.g., `[]struct{ Key string; Value int }` to `{"a":1,"b":2,"c":3}`

jsonutil.MarshalEntries(len(entries), func(i int) *jsonutil.Entry {
  return &jsonutil.Entry{
    Key:   entries[i].Key,
    Value: entries[i].Int,
  }
})
Example
// type IntEntry struct {
//   Key string
//   Int  int
// }

entries := []*IntEntry{
	{
		Key: "a",
		Int: 42,
	},
	{
		Key: "b",
		Int: 99,
	},
}

bs, _ := jsonutil.MarshalEntries(len(entries), func(i int) *jsonutil.Entry {
	return &jsonutil.Entry{
		Key:   entries[i].Key,
		Value: entries[i].Int,
	}
})
fmt.Println(string(bs))
Output:

{"a":42,"b":99}
Example (MultiFields)
// type IntEntry struct {
//   Key string
//   Int  int
// }

entries := []*MultiFieldEntry{
	{
		Key: "foo",
		A:   "A1",
		B:   42,
	},
	{
		Key: "bar",
		A:   "A2",
		B:   99,
	},
}

bs, _ := jsonutil.MarshalEntries(len(entries), func(i int) *jsonutil.Entry {
	return &jsonutil.Entry{
		Key:   entries[i].Key,
		Value: entries[i],
	}
})
fmt.Println(string(bs))
Output:

{"foo":{"a":"A1","b":42},"bar":{"a":"A2","b":99}}

func UnmarshalEntries

func UnmarshalEntries(bs []byte, resolveEntry func(key string, data []byte) error) error

UnmarshalEntries is a utility function to unmarshal JSON objects into slices in the same order.

e.g., unmarshal `{"a":1,"b":2,"c":3}` to `[&{Key:"a", Int:1},...]`

jsonutil.UnmarshalEntries([]byte(`{"a":1,"b":2,"c":3}`), func(key string, data []byte) error {
  entry := &IntEntry{
    Key: key,
  }
  entries = append(entries, entry)
  return json.Unmarshal(data, &entry.Int)
})
Example
// type IntEntry struct {
//   Key string
//   Int  int
// }

var entries []*IntEntry
if err := jsonutil.UnmarshalEntries([]byte(`{"a":1,"b":2,"c":3}`), func(key string, data []byte) error {
	entry := &IntEntry{
		Key: key,
	}
	entries = append(entries, entry)
	return json.Unmarshal(data, &entry.Int)
}); err != nil {
	fmt.Printf("error: %v", err)
}

for i, v := range entries {
	fmt.Printf("#%d: %+v\n", i, v)
}
Output:

#0: &{Key:a Int:1}
#1: &{Key:b Int:2}
#2: &{Key:c Int:3}
Example (MultiFields)
// type MultiFieldEntry struct {
//   Key string `json:"-"`
//   A   string `json:"a"`
//   B   int    `json:"b"`
// }

var entries []*MultiFieldEntry
if err := jsonutil.UnmarshalEntries(
	[]byte(`{"foo":{"a":"A1","b":42},"bar":{"a":"A2","b":99},"buz":null}`),
	func(key string, data []byte) error {
		var entry *MultiFieldEntry
		if err := json.Unmarshal(data, &entry); err != nil || entry == nil {
			return err
		}
		entry.Key = key
		entries = append(entries, entry)
		return nil
	},
); err != nil {
	fmt.Printf("error: %v", err)
}

for i, v := range entries {
	fmt.Printf("#%d: %+v\n", i, v)
}
Output:

#0: &{Key:foo A:A1 B:42}
#1: &{Key:bar A:A2 B:99}

Types

type Entries

type Entries []*Entry

Entries represents list of ordered JSON object key / value pair.

func (Entries) MarshalJSON

func (ls Entries) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface for list of ordered JSON object entries.

func (*Entries) UnmarshalJSON

func (ls *Entries) UnmarshalJSON(bs []byte) error

UnmarshalJSON implements json.Unmarshaler interface for list of ordered JSON object entries. It unmarshal JSON objects into slices in the same order.

type Entry

type Entry struct {
	Key   string
	Value interface{}
}

Entry represents a JSON object key / value pair.

type IntBool added in v1.2.0

type IntBool bool

IntBool is bool value represented by int.

func (IntBool) Bool added in v1.2.0

func (b IntBool) Bool() bool

Bool returns value as bool.

func (IntBool) MarshalJSON added in v1.2.0

func (s IntBool) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

Example
ls := []IntBool{
	true,
	false,
}
bs, err := json.Marshal(ls)
if err != nil {
	fmt.Printf("error: %v", err)
}

fmt.Printf("%s", bs)
Output:

[1,0]

func (*IntBool) UnmarshalJSON added in v1.2.0

func (b *IntBool) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

Example
var ls []IntBool
err := json.Unmarshal([]byte(`[1,0,null]`), &ls)
if err != nil {
	fmt.Printf("error: %v", err)
}
for i, v := range ls {
	fmt.Printf("#%d: %#v\n", i, v)
}
Output:

#0: true
#1: false
#2: false

type IntString added in v1.2.0

type IntString string

IntString is string value represented by int. If it is an empty string, JSON string will be `null`.

func (IntString) MarshalJSON added in v1.2.0

func (s IntString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

Example
ls := []IntString{
	"42",
	"0",
	"-1",
	"",
}
bs, err := json.Marshal(ls)
if err != nil {
	fmt.Printf("error: %v", err)
}

fmt.Printf("%s", bs)
Output:

[42,0,-1,null]

func (IntString) String added in v1.2.0

func (s IntString) String() string

String returns value as string.

func (*IntString) UnmarshalJSON added in v1.2.0

func (s *IntString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

Example
var ls []IntString
err := json.Unmarshal([]byte(`[42,0,-1,null]`), &ls)
if err != nil {
	fmt.Printf("error: %v", err)
}
for i, v := range ls {
	fmt.Printf("#%d: %#v\n", i, v)
}
Output:

#0: "42"
#1: "0"
#2: "-1"
#3: ""

type RawMessage added in v1.1.0

type RawMessage json.RawMessage

RawMessage is a raw encoded JSON value. It extends encoding/json.RawMessage.

func (RawMessage) Equal added in v1.1.0

func (m RawMessage) Equal(data []byte) bool

Equal returns whether m equals data.

Example
var v RawMessage
if err := json.Unmarshal([]byte(`[]`), &v); err != nil {
	fmt.Printf("error: %v", v)
}

fmt.Printf("value: %s\n", v)
fmt.Printf("is empty array: %v\n", v.Equal(EmptyArray))
Output:

value: []
is empty array: true

func (RawMessage) MarshalJSON added in v1.1.0

func (m RawMessage) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

It was copied from json.RawMessage. See, https://cs.opensource.google/go/go/+/refs/tags/go1.16.4:src/encoding/json/stream.go;l=263

func (*RawMessage) UnmarshalJSON added in v1.1.0

func (m *RawMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *m to a copy of data.

It was copied from json.RawMessage. See, https://cs.opensource.google/go/go/+/refs/tags/go1.16.4:src/encoding/json/stream.go;l=271

type StringOrFalse added in v1.5.0

type StringOrFalse struct {
	IsString bool
	Value    string
}

StringOrFalse is JSON value that represents string or `false`.

func (StringOrFalse) MarshalJSON added in v1.5.0

func (s StringOrFalse) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

Example
ls := []StringOrFalse{
	{
		IsString: true,
		Value:    "foo",
	},
	{
		IsString: true,
		Value:    "",
	},
	{
		IsString: false,
		Value:    "",
	},
	{
		IsString: false,
		Value:    "foo",
	},
}

bs, err := json.Marshal(ls)
if err != nil {
	fmt.Printf("error: %v", err)
}

fmt.Printf("%s", bs)
Output:

["foo","",false,false]

func (StringOrFalse) String added in v1.5.0

func (s StringOrFalse) String() string
Example
ls := []StringOrFalse{
	{
		IsString: true,
		Value:    "foo",
	},
	{
		IsString: true,
		Value:    "",
	},
	{
		IsString: false,
		Value:    "",
	},
	{
		IsString: false,
		Value:    "foo",
	},
}

for i, v := range ls {
	fmt.Printf("#%d: %#v\n", i, v.String())
}
Output:

#0: "foo"
#1: ""
#2: ""
#3: ""

func (*StringOrFalse) UnmarshalJSON added in v1.5.0

func (s *StringOrFalse) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

Example
var ls []StringOrFalse
if err := json.Unmarshal([]byte(`["foo","",false]`), &ls); err != nil {
	fmt.Printf("error: %v", err)
}

for i, v := range ls {
	fmt.Printf("#%d: %v, %#v\n", i, v.IsString, v.Value)
}
Output:

#0: true, "foo"
#1: true, ""
#2: false, ""

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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