Skip to Content
Mino

jsonx · JSON

Encode JSON, read complete documents, and configure a codec.

简体中文 ↗

Uses encoding/json by default. Use it independently.

Encode and decode

main.go
package main

import (
	"fmt"
	"log"

	"github.com/hainuoli/mino/core/jsonx"
)

type User struct {
	Name string `json:"name"`
}

func main() {
	data, err := jsonx.Marshal(User{Name: "Mino"})
	if err != nil {
		log.Fatal(err)
	}

	var user User
	if err := jsonx.Unmarshal(data, &user); err != nil {
		log.Fatal(err)
	}
	fmt.Println(user.Name)
}

Complete example · cd examples && go run ./packages/jsonx

Mino

Choose an input or output

FunctionUse
MarshalEncode to []byte
MarshalToStringEncode to a string
UnmarshalDecode []byte
UnmarshalFromStringDecode a string
UnmarshalFromReaderRead a complete Reader and decode it
ValidCheck for a complete JSON document

Read from a Reader

func readUser(r io.Reader) (User, error) {
	var user User
	err := jsonx.UnmarshalFromReader(r, &user)
	return user, err
}

Reads to EOF without closing the Reader. Use httpx for bounded HTTP body parsing.

Replace the codec

Implement the three methods of jsonx.Codec:

type Codec interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
	Valid(data []byte) bool
}
func configureJSON(codec jsonx.Codec) error {
	return jsonx.SetCodec(codec)
}
  • Configure at startup, before concurrent use. The codec must support concurrent calls.
  • Configuration is process-wide and also affects JSON operations in httpx.
  • A nil codec returns an error and preserves the current configuration.

API · Packages and defaults

On this page