jsonx

package
v1.2.5 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package jsonx provides helpers for decoding JSON from common sources.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode[T any](r io.Reader, options ...DecodeOption) (*T, error)

Decode decodes JSON from an io.Reader into T. The caller is responsible for closing the reader if applicable.

Returns an error if decoding fails.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	r := strings.NewReader(`{"name":"Alice","age":30}`)

	p, _ := jsonx.Decode[person](r)

	fmt.Println(p.Name, p.Age)
}
Output:
Alice 30

func DecodeBytes

func DecodeBytes[T any](b []byte, options ...DecodeOption) (*T, error)

DecodeBytes decodes JSON from a byte slice into T.

Returns an error if decoding fails.

Example
package main

import (
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	p, _ := jsonx.DecodeBytes[person]([]byte(`{"name":"Alice","age":30}`))

	fmt.Println(p.Name, p.Age)
}
Output:
Alice 30

func DecodeFromFile added in v1.2.1

func DecodeFromFile[T any](path string, options ...DecodeOption) (*T, error)

DecodeFromFile decodes JSON from a file path into T.

Returns an error if decoding fails.

Example
package main

import (
	"fmt"
	"os"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	f, _ := os.CreateTemp("", "snk-*.json")

	defer func() { _ = os.Remove(f.Name()) }()

	_ = os.WriteFile(f.Name(), []byte(`{"name":"Alice","age":30}`), 0o600)

	p, _ := jsonx.DecodeFromFile[person](f.Name())

	fmt.Println(p.Name, p.Age)
}
Output:
Alice 30

func DecodeString

func DecodeString[T any](s string, options ...DecodeOption) (*T, error)

DecodeString decodes JSON from a string into T.

Returns an error if decoding fails.

Example
package main

import (
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	p, _ := jsonx.DecodeString[person](`{"name":"Alice","age":30}`)

	fmt.Println(p.Name, p.Age)
}
Output:
Alice 30

func Encode added in v1.2.0

func Encode[T any](writer io.Writer, value T, options ...EncodeOption) error

Encode encodes value as JSON into the provided io.Writer.

Returns an error if encoding fails.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	var buf strings.Builder

	_ = jsonx.Encode(&buf, person{Name: "Alice", Age: 30})

	fmt.Print(buf.String())
}
Output:
{"name":"Alice","age":30}
Example (WithEscapeHTML)
package main

import (
	"fmt"
	"strings"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

func main() {
	type link struct {
		URL string `json:"url"`
	}

	var buf strings.Builder

	_ = jsonx.Encode(&buf, link{URL: "https://example.com?a=1&b=2"}, jsonx.WithEscapeHTML())

	fmt.Print(buf.String())
}
Output:
{"url":"https://example.com?a=1\u0026b=2"}
Example (WithIndent)
package main

import (
	"fmt"
	"strings"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	var buf strings.Builder

	_ = jsonx.Encode(&buf, person{Name: "Alice", Age: 30}, jsonx.WithIndent("  "))

	fmt.Print(buf.String())
}
Output:
{
  "name": "Alice",
  "age": 30
}

func EncodeBytes added in v1.2.0

func EncodeBytes[T any](value T, options ...EncodeOption) ([]byte, error)

EncodeBytes encodes a value as JSON and returns the result as a byte slice.

Returns an error if encoding fails.

Example
package main

import (
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	b, _ := jsonx.EncodeBytes(person{Name: "Alice", Age: 30})

	fmt.Print(string(b))
}
Output:
{"name":"Alice","age":30}

func EncodeString added in v1.2.0

func EncodeString[T any](value T, options ...EncodeOption) (string, error)

EncodeString encodes a value as JSON and returns the result as a string.

Returns an error if encoding fails.

Example
package main

import (
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	s, _ := jsonx.EncodeString(person{Name: "Alice", Age: 30})

	fmt.Print(s)
}
Output:
{"name":"Alice","age":30}

func EncodeToFile added in v1.2.1

func EncodeToFile[T any](path string, value T, options ...EncodeOption) error

EncodeToFile encodes a value as JSON into the file at the given path.

Returns an error if encoding fails.

Example
package main

import (
	"fmt"
	"os"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	f, _ := os.CreateTemp("", "snk-*.json")

	defer func() { _ = os.Remove(f.Name()) }()

	_ = f.Close()

	_ = jsonx.EncodeToFile(f.Name(), person{Name: "Alice", Age: 30})

	p, _ := jsonx.DecodeFromFile[person](f.Name())

	fmt.Println(p.Name, p.Age)
}
Output:
Alice 30

Types

type DecodeOption added in v1.2.0

type DecodeOption func(options *DecodeOptions)

DecodeOption is a function that configures DecodeOptions.

func WithStrictDecoding

func WithStrictDecoding() DecodeOption

WithStrictDecoding disallows unknown fields when decoding JSON.

Example
package main

import (
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

type person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	_, err := jsonx.DecodeString[person](
		`{"name":"Alice","age":30,"role":"admin"}`,
		jsonx.WithStrictDecoding(),
	)

	fmt.Println(err != nil)
}
Output:
true

func WithUseNumber

func WithUseNumber() DecodeOption

WithUseNumber causes the decoder to unmarshal JSON numbers as json.Number instead of float64. This is useful when precision matters or when the caller wants to determine the numeric type themselves.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/SharkByteSoftware/go-snk/jsonx"
)

func main() {
	type record struct {
		Value any `json:"value"`
	}

	r, _ := jsonx.DecodeString[record](`{"value":12345}`, jsonx.WithUseNumber())

	num, ok := r.Value.(json.Number)

	fmt.Println(ok, num)
}
Output:
true 12345

type DecodeOptions

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

DecodeOptions contains the configuration options for JSON decoding.

type EncodeOption added in v1.2.0

type EncodeOption func(options *EncodeOptions)

EncodeOption is a function that configures EncodeOptions.

func WithEscapeHTML added in v1.2.0

func WithEscapeHTML() EncodeOption

WithEscapeHTML enables escaping of HTML characters (<, >, &) in the output. By default HTML escaping is disabled, unlike the standard library which enables it. Enable only when the output may be embedded in HTML.

func WithIndent added in v1.2.0

func WithIndent(indent string) EncodeOption

WithIndent enables pretty-printing with the given indent string per level. Common values are "\t" or " " (two spaces).

type EncodeOptions added in v1.2.0

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

EncodeOptions contains the configuration options for JSON encoding.

Jump to

Keyboard shortcuts

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