sjon

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2024 License: MIT Imports: 11 Imported by: 0

README

go-sjon

go-sjon provides JSON utilities. As of now, it only provides customizable JSON serializer.

Serializer

Serializer is a customizable json serializer.

Example: print struct key in lower camel case

type User struct {
    FirstName string
    LastName string
}

s := sjon.NewSerializer().
    With(sjon.StructKeyNamer(strcase.ToLowerCamel))
    
b, _ := s.Marshal(User{
    FirstName: "Betty",
    LastName: "Miller",
})
fmt.Println(string(b))
// Output: {"firstName":"Betty","lastName":"Miller"}

Example: print only date for time.Time

s := sjon.NewSerializer().
    With(sjon.Replacer(func(d time.Time) string {
        return d.Format("2006-01-02")
    }))
    
b, _ := s.Marshal([]time.Time{
        time.Date(2024, 10, 20, 1, 2, 3, 4, time.UTC),
        time.Date(2024, 10, 21, 1, 2, 3, 4, time.UTC),
        time.Date(2024, 10, 22, 1, 2, 3, 4, time.UTC),
    })
fmt.Println(string(b))
// Output: ["2024-10-20","2024-10-21","2024-10-22"]

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config[T any] func(v T) T

Config is used to configure instances Usual user don't need to know about it

func Replacer

func Replacer[Before, After any](replace func(Before) After) Config[Serializer]

Replacer takes a replace function and returns a config Serializer with Replacer applies the replace function into values with replace function's argument type

Example
s := sjon.NewSerializer().
	With(sjon.Replacer(func(d time.Time) string {
		return d.Format("2006-01-02")
	}))

b, _ := s.Marshal([]time.Time{
	time.Date(2024, 10, 20, 1, 2, 3, 4, time.UTC),
	time.Date(2024, 10, 21, 1, 2, 3, 4, time.UTC),
	time.Date(2024, 10, 22, 1, 2, 3, 4, time.UTC),
})
fmt.Println(string(b))
Output:
["2024-10-20","2024-10-21","2024-10-22"]

func StructKeyNamer

func StructKeyNamer(keyNamer func(string) string) Config[Serializer]

StructKeyNamer returns a Config that changes how Serializer serializes struct key

Example
type User struct {
	FirstName string
	LastName  string
}

s := sjon.NewSerializer().
	With(sjon.StructKeyNamer(strcase.ToLowerCamel))

b, _ := s.Marshal(User{
	FirstName: "Betty",
	LastName:  "Miller",
})
fmt.Println(string(b))
Output:
{"firstName":"Betty","lastName":"Miller"}

type Serializer

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

Serializer provides JSON serialization with non-invasive customization

func NewSerializer

func NewSerializer() Serializer

NewSerializer returns a new Serializer

func (Serializer) Marshal

func (s Serializer) Marshal(v any) ([]byte, error)

func (Serializer) With

func (s Serializer) With(config Config[Serializer]) Serializer

With returns a new Serializer with passed configuration