json

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

json

A small library that puts JSON encoding and decoding behind a pluggable provider, so an application chooses its JSON engine once and every package that encodes through this one follows.

Go's encoding/json is correct and everywhere, but it is not the fastest engine, and a large application ends up with JSON calls scattered through many packages and libraries. Swapping the engine means touching every one of them. json gives those packages one place to call instead. By default every call goes to encoding/json. When the application activates a provider, such as one backed by sonic, every call made through this package moves to it, including calls from libraries that know nothing about the provider.

Module piko.sh/json. Go 1.27. Apache-2.0. It depends on nothing outside the standard library.

Install

go get piko.sh/json

Usage

Packages call the package-level functions, as they would call encoding/json.

package main

import (
	"fmt"

	"piko.sh/json"
)

type order struct {
	ID   int64    `json:"id"`
	Tags []string `json:"tags"`
}

func main() {
	encoded, err := json.Marshal(order{ID: 1, Tags: []string{"gift"}})
	if err != nil {
		panic(err)
	}

	var decoded order
	if err := json.Unmarshal(encoded, &decoded); err != nil {
		panic(err)
	}
	fmt.Println(string(encoded), decoded.ID)
}

The application activates a provider once while it starts, before it serves work.

provider.Activate() // every json call from here on uses the provider

A library that would rather be handed its encoder takes an API instead.

type Store struct {
	codec json.API
}

func NewStore(codec json.API) *Store {
	if pretoucher, ok := codec.(json.Pretoucher); ok {
		_ = pretoucher.Pretouch(reflect.TypeFor[order]())
	}
	return &Store{codec: codec}
}

store := NewStore(json.Freeze(json.Config{}))

What it provides

  • Marshal, Unmarshal, MarshalIndent, MarshalString, UnmarshalString, ValidString, NewEncoder and NewDecoder call the active provider, which is encoding/json until one is activated.
  • Provider is what an engine implements. Its Activate method replaces the package-level functions and the ConfigStd and ConfigDefault APIs with the engine's own. FreezeImpl is the hook a provider replaces to build frozen APIs.
  • API is an encoder and decoder value with the same operations, for code that takes its encoder as a dependency. ConfigStd escapes HTML like encoding/json; ConfigDefault does not.
  • Freeze(Config) returns an API for a Config (CopyString, UseInt64, EscapeHTML, SortMapKeys). It resolves on its first call, so an API frozen before the application activates its provider still uses that provider.
  • Pretouch(reflect.Type) compiles a type's codec ahead of its first use, for engines that compile codecs. Pretoucher is the same operation on an API, which every API this package and its providers return implements.
  • DrainPretouchBuffer returns the types pretouched before a provider was active. A provider calls it in Activate and pretouches each one.
  • Encoder and Decoder are the streaming interfaces.

Semantics

  • Until a provider is activated, everything is encoding/json. Output matches it, except that ConfigDefault does not escape HTML.
  • Frozen APIs bind late. Freeze returns an API that resolves through FreezeImpl on its first call, then keeps that engine. Freeze APIs in init functions or constructors freely; they use the provider active when they are first used.
  • Pretouching before activation is not lost. Pretouch records the type until a provider that compiles codecs is active, and the provider pretouches every recorded type when it activates, so packages may pretouch from init in any order. With encoding/json alone it records the type and does nothing else.
  • Pretouch is safe for concurrent use. Activate is not. Activation replaces package-level functions, so run it once while the application starts, before other goroutines encode or decode.

Writing a provider

A provider replaces the package-level functions in Activate and then pretouches what was recorded.

func (sonicProvider) Activate() {
	json.Marshal = sonic.Marshal
	json.Unmarshal = sonic.Unmarshal
	// ... the remaining functions, ConfigStd, ConfigDefault and FreezeImpl
	json.Pretouch = sonicPretouch
	for _, t := range json.DrainPretouchBuffer() {
		_ = sonicPretouch(t)
	}
}

Piko ships a provider backed by sonic in piko.sh/piko/wdk/json/json_provider_sonic.

Development

make test        # run the test suite
make test-race   # run it under the race detector
make crossarch   # cross-compile for arm64

Run make help for the full list of targets.

Documentation

Overview

Package json wraps JSON encoding and decoding behind a pluggable Provider, so an application can swap encoding/json for a faster engine in one place and every library that encodes through this package follows.

By default every operation delegates to encoding/json. A provider, such as Piko's sonic provider (piko.sh/piko/wdk/json/json_provider_sonic), replaces the package-level functions (Marshal, Unmarshal and the rest) and the ConfigStd and ConfigDefault APIs when its Activate method runs, which an application does once while it starts.

Dependency injection

A library that would rather be handed an encoder than reach for package state takes an API. Freeze returns one that resolves lazily on its first call, so an API frozen before the application activates its provider still uses that provider. An API also implements Pretoucher, which a library checks for to compile the codecs of the types it decodes ahead of their first use.

Pretouching

Pretouch compiles the codec for a type ahead of its first use, for a provider whose codecs are compiled, such as sonic's. Before such a provider is active the type is recorded, and the provider pretouches every recorded type when it activates, so packages may call Pretouch from init functions in any order. Pretouch is safe for concurrent use.

Activating a provider is not safe while other goroutines encode or decode, so activate it before serving work.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Marshal encodes v as JSON bytes.
	Marshal func(v any) ([]byte, error)

	// Unmarshal decodes JSON data into v.
	Unmarshal func(data []byte, v any) error

	// MarshalIndent encodes v as indented JSON bytes.
	MarshalIndent func(v any, prefix, indent string) ([]byte, error)

	// MarshalString encodes v as a JSON string.
	MarshalString func(v any) (string, error)

	// UnmarshalString decodes a JSON string into v.
	UnmarshalString func(s string, v any) error

	// NewEncoder creates a streaming JSON encoder writing to w.
	NewEncoder func(w io.Writer) Encoder

	// NewDecoder creates a streaming JSON decoder reading from r.
	NewDecoder func(r io.Reader) Decoder

	// FreezeImpl creates a concrete API from a Config. Providers replace FreezeImpl to
	// supply their own frozen configuration; callers should use Freeze instead, which
	// returns a lazy proxy.
	FreezeImpl func(config Config) API
)
View Source
var (
	// ValidString reports whether s is valid JSON.
	ValidString func(s string) bool

	// Pretouch pre-compiles JSON codecs for the given type. Before a provider is activated,
	// calls are buffered and drained when DrainPretouchBuffer is called during provider
	// activation.
	Pretouch func(t reflect.Type) error
)

Functions

func DrainPretouchBuffer

func DrainPretouchBuffer() []reflect.Type

DrainPretouchBuffer returns all types that were buffered by Pretouch calls before provider activation, then clears the buffer. Providers should call this during Activate and pretouch each returned type.

Returns []reflect.Type which contains the buffered types, or nil if empty.

Types

type API

type API interface {
	// Marshal serialises v into JSON bytes.
	//
	// Takes v (any) which is the value to serialise.
	//
	// Returns []byte which is the JSON-encoded output.
	// Returns error when serialisation fails.
	Marshal(v any) ([]byte, error)

	// Unmarshal deserialises JSON data into v.
	//
	// Takes data ([]byte) which is the raw JSON input.
	// Takes v (any) which is the target to populate.
	//
	// Returns error when deserialisation fails.
	Unmarshal(data []byte, v any) error

	// MarshalIndent serialises v into indented JSON bytes.
	//
	// Takes v (any) which is the value to serialise.
	// Takes prefix (string) which is prepended to each line.
	// Takes indent (string) which is the indentation unit.
	//
	// Returns []byte which is the indented JSON output.
	// Returns error when serialisation fails.
	MarshalIndent(v any, prefix, indent string) ([]byte, error)

	// NewEncoder creates a streaming JSON encoder writing to w.
	//
	// Takes w (io.Writer) which receives the encoded JSON.
	//
	// Returns Encoder which wraps the underlying provider.
	NewEncoder(w io.Writer) Encoder

	// NewDecoder creates a streaming JSON decoder reading from r.
	//
	// Takes r (io.Reader) which supplies the raw JSON.
	//
	// Returns Decoder which wraps the underlying provider.
	NewDecoder(r io.Reader) Decoder
}

API is a frozen JSON configuration providing encode and decode operations.

var (
	// ConfigStd is a standard-library-compatible configuration. It escapes HTML characters
	// and produces output consistent with encoding/json defaults.
	ConfigStd API

	// ConfigDefault is the high-performance default configuration. It does not escape HTML
	// characters.
	ConfigDefault API
)

func Freeze

func Freeze(config Config) API

Freeze creates a frozen API from a Config. The returned API resolves lazily on first method call, picking up whichever provider is active at that time; this allows frozen configs created in init() to benefit from providers activated later during bootstrap.

Takes config (Config) which specifies the encoding behaviour.

Returns API which lazily resolves to the active provider on first use.

type Config

type Config struct {
	// CopyString copies decoded strings instead of referencing the source buffer, preventing
	// memory issues when decoded objects outlive the original JSON data. Sonic-only.
	CopyString bool

	// UseInt64 decodes JSON numbers as int64 when possible. Sonic-only.
	UseInt64 bool

	// EscapeHTML escapes HTML characters in JSON strings.
	EscapeHTML bool

	// SortMapKeys produces deterministic output by sorting map keys.
	SortMapKeys bool
}

Config describes JSON encoding behaviour. When the sonic provider is active, all fields are honoured; with the stdlib fallback, only EscapeHTML is respected and the remaining fields are silently ignored.

type Decoder

type Decoder interface {
	// Decode reads the next JSON value from the underlying stream into v.
	//
	// Takes v (any) which is a pointer to the destination value.
	//
	// Returns error when the stream cannot be read or the value cannot be parsed.
	Decode(v any) error
}

Decoder reads JSON values from an input stream.

type Encoder

type Encoder interface {
	// Encode serialises v as JSON and writes it to the underlying stream.
	//
	// Takes v (any) which is the value to serialise.
	//
	// Returns error when the value cannot be serialised or written.
	Encode(v any) error
}

Encoder writes JSON values to an output stream.

type Pretoucher

type Pretoucher interface {
	// Pretouch compiles the codec for t, or records t until a provider that compiles
	// codecs is active.
	//
	// Takes t (reflect.Type) which is the type to compile for.
	//
	// Returns error when the codec cannot be compiled.
	Pretouch(t reflect.Type) error
}

Pretoucher is implemented by an API that can compile the codec for a type before its first use, as Freeze's result, ConfigStd and ConfigDefault all do. A library given an API through dependency injection checks for it to pretouch the types it decodes.

type Provider

type Provider interface {
	// Activate replaces all package-level function and API variables with this provider's
	// implementations. It is called once during application bootstrap.
	Activate()
}

Provider supplies JSON encoding and decoding operations. Implementations replace the default stdlib functions when activated.

Jump to

Keyboard shortcuts

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