Help us shape the future of Go! Take the 2026 Go Developer Survey

json

package
v1.74.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 8 Imported by: 4

README

Package json

Пакет json расширяет библиотеку jsoniter с дополнительными возможностями:

  • Кастомное форматирование времени
  • Автоматическое преобразование имен полей camelCase, если не указан json тэг у структуры
  • Совместимость с API стандартной библиотеки encoding/json

Functions

Marshal(v any) ([]byte, error)

Преобразовать переданный объект в массив байт json-формата.

Unmarshal(data []byte, ptr any) error

Преобразовать объект обратно из массива байт json-формата.

NewEncoder(w io.Writer) *jsoniter.Encoder

Создание потокового энкодера.

NewDecoder(r io.Reader) *jsoniter.Decoder

Создание потокового декодера.

EncodeInto(w io.Writer, value any) error

Оптимизированная запись в поток с автоматическим сбросом буфера

Usage

Default usage flow
package main

import (
	"log"
	"time"

	"github.com/txix-open/isp-kit/json"
)

type Message struct {
	Text      string
	CreatedAt time.Time
}

func main() {
	msg := Message{
		Text:      "hi x.x",
		CreatedAt: time.Now().UTC(),
	}
	/* data: {"text":"hi x.x","createdAt":"2009-11-10T23:00:00Z"} */
	data, err := json.Marshal(msg)
	if err != nil {
		log.Fatal(err)
	}

	var decoded Message
	err = json.Unmarshal(data, &decoded)
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package json provides a high-performance JSON encoder/decoder based on jsoniter.

It extends the standard library with:

  • Custom time.Time formatting (RFC3339 with milliseconds)
  • Automatic camelCase conversion for struct field names
  • Full API compatibility with encoding/json

This package is safe for concurrent use by multiple goroutines.

Index

Constants

View Source
const (
	FullDateFormat = "2006-01-02T15:04:05.999Z07:00"
)

FullDateFormat is the default layout for time.Time serialization.

It uses RFC3339 with millisecond precision: "2006-01-02T15:04:05.999Z07:00"

Variables

This section is empty.

Functions

func EncodeInto

func EncodeInto(w io.Writer, value any) error

EncodeInto encodes a value into a writer, appending a newline.

This is an optimized function for line-delimited JSON (e.g., NDJSON).

func Marshal

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

Marshal returns the JSON encoding of v.

It uses the default jsoniter configuration with time formatting and camelCase field naming.

func NewDecoder

func NewDecoder(r io.Reader) *jsoniter.Decoder

NewDecoder returns a new decoder that reads from r.

func NewEncoder

func NewEncoder(w io.Writer) *jsoniter.Encoder

NewEncoder returns a new encoder that writes to w.

func Unmarshal

func Unmarshal(data []byte, ptr any) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by ptr.

See encoding/json.Unmarshal for details on the conversion.

Types

type RawMessage

type RawMessage = json.RawMessage

RawMessage is a raw encoded JSON value. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding. It is an alias for encoding/json.RawMessage.

type TimeCodec

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

TimeCodec is a jsoniter extension for custom time.Time encoding and decoding.

It formats time values using a configurable layout string.

func NewTimeCodec

func NewTimeCodec(format string) *TimeCodec

NewTimeCodec returns a new TimeCodec with the specified format layout.

The format string follows Go's time.Parse conventions (see time.Layout).

func (*TimeCodec) Decode

func (codec *TimeCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator)

Decode parses a JSON string into a time.Time value.

It reports an error to the iterator if the string cannot be parsed.

func (*TimeCodec) Encode

func (codec *TimeCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream)

Encode writes a time.Time value as a formatted JSON string.

The time is formatted using the codec's layout string.

func (*TimeCodec) IsEmpty

func (codec *TimeCodec) IsEmpty(ptr unsafe.Pointer) bool

IsEmpty checks if a time.Time value is zero.

It returns true if the time is the zero value.

Jump to

Keyboard shortcuts

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