prettyjson

package
v1.2.123 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2025 License: MIT Imports: 19 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compact

func Compact(dst *bytes.Buffer, src []byte) error

Compact appends to dst the JSON-encoded src with insignificant space characters elided.

func Indent

func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error

Indent appends to dst an indented form of the JSON-encoded src. Each element in a JSON object or array begins on a new, indented line beginning with prefix followed by one or more copies of indent according to the indentation nesting. The data appended to dst does not begin with the prefix nor any indentation, to make it easier to embed inside other formatted JSON data. Although leading space characters (space, tab, carriage return, newline) at the beginning of src are dropped, trailing space characters at the end of src are preserved and copied to dst. For example, if src has no trailing spaces, neither will dst; if src ends in a trailing newline, so will dst.

func Marshal

func Marshal(v any, opts ...EncOptsOption) ([]byte, error)

Marshal returns the JSON encoding of v, and support truncate.

Example
package main

import (
	"fmt"
	"os"

	"github.com/searKing/golang/go/encoding/prettyjson"
)

func main() {
	type ColorGroup struct {
		ID            int
		Name          string
		LongName      string
		Colors        []string
		ColorById     map[string]string
		ColorEnumById map[string]int
		Url           string
		LongUrl       string
		Empty         struct {
			ID   int
			Name string
		}
	}
	group := ColorGroup{
		ID:            1,
		Name:          "Reds",
		LongName:      "The quick brown fox jumps over the lazy dog",
		Colors:        []string{"The quick brown fox jumps over the lazy dog", "Crimson", "Red", "Ruby", "Maroon"},
		ColorById:     map[string]string{"0": "red", "1": "green", "2": "blue", "3": "white"},
		ColorEnumById: map[string]int{"0": 0, "1": 1, "2": 2, "3": 3},
		Url:           "https://example.com/tests/1?foo=1&bar=baz",
		LongUrl:       "https://example.com/tests/1.html?foo=1&bar=baz&a=0&b=1&c=2&d=3#paragraph",
	}
	{
		b, err := prettyjson.Marshal(group,
			prettyjson.WithEncOptsTruncateString(10),
			prettyjson.WithEncOptsTruncateBytes(10),
			prettyjson.WithEncOptsTruncateSliceOrArray(2),
			prettyjson.WithEncOptsTruncateMap(2),
			prettyjson.WithEncOptsTruncateUrl(true),
			prettyjson.WithEncOptsEscapeHTML(false),
			prettyjson.WithEncOptsOmitEmpty(true))
		if err != nil {
			fmt.Println("error:", err)
		}
		_, _ = os.Stdout.Write(b)
		_, _ = os.Stdout.Write([]byte("\n"))
	}
	{
		b, err := prettyjson.Marshal(group,
			prettyjson.WithEncOptsTruncateString(20),
			prettyjson.WithEncOptsTruncateStringIfMoreThan(10),
			prettyjson.WithEncOptsTruncateBytes(20),
			prettyjson.WithEncOptsTruncateBytesIfMoreThan(10),
			prettyjson.WithEncOptsTruncateSliceOrArray(4),
			prettyjson.WithEncOptsTruncateSliceOrArrayIfMoreThan(2),
			prettyjson.WithEncOptsTruncateMap(4),
			prettyjson.WithEncOptsTruncateMapIfMoreThan(2),
			prettyjson.WithEncOptsTruncateUrl(true),
			prettyjson.WithEncOptsEscapeHTML(false),
			prettyjson.WithEncOptsForceLongUrl(false),
			prettyjson.WithEncOptsOmitEmpty(true))
		if err != nil {
			fmt.Println("error:", err)
		}
		_, _ = os.Stdout.Write(b)
		_, _ = os.Stdout.Write([]byte("\n"))
	}

}
Output:

{"ID":1,"Name":"Reds","LongName":"The quick ...43 chars","Colors":["The quick ...43 chars","Crimson","...5 elems"],"ColorById":{"0":"red","1":"green","2...4 pairs":"blue"},"ColorEnumById":{"0":0,"1":1,"2...4 pairs":2},"Url":"https://example.com/tests/1?foo=1&bar=baz","LongUrl":"https://example.com/tests/1.html...72 chars,6Q9F]"}
{"ID":1,"Name":"Reds","LongName":"The quick brown fox ...43 chars","Colors":["The quick brown fox ...43 chars","Crimson","Red","Ruby","...5 elems"],"ColorById":{"0":"red","1":"green","2":"blue","3":"white"},"ColorEnumById":{"0":0,"1":1,"2":2,"3":3},"Url":"https://example.com/tests/1?foo=1&bar=baz","LongUrl":"https://example.com/tests/1.html...72 chars,6Q9F]"}

func MarshalIndent

func MarshalIndent(v any, prefix, indent string, opts ...EncOptsOption) ([]byte, error)

MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

func Valid

func Valid(data []byte) bool

Valid reports whether data is a valid JSON encoding.

Types

type EmptyEncOptsOption

type EmptyEncOptsOption struct{}

EmptyEncOptsOption does not alter the configuration. It can be embedded in another structure to build custom options.

This API is EXPERIMENTAL.

type EncOptsOption

type EncOptsOption interface {
	// contains filtered or unexported methods
}

A EncOptsOption sets options.

func WithEncOptsEscapeHTML

func WithEncOptsEscapeHTML(v bool) EncOptsOption

WithEncOptsEscapeHTML sets escapeHTML in encOpts. escapeHTML causes '<', '>', and '&' to be escaped in JSON strings.

func WithEncOptsForceLongUrl added in v1.2.121

func WithEncOptsForceLongUrl(v bool) EncOptsOption

WithEncOptsForceLongUrl sets forceLongUrl in encOpts. force long url

func WithEncOptsOmitEmpty added in v1.2.112

func WithEncOptsOmitEmpty(v bool) EncOptsOption

WithEncOptsOmitEmpty sets omitEmpty in encOpts. omit empty value

func WithEncOptsOmitStatistics added in v1.2.121

func WithEncOptsOmitStatistics(v bool) EncOptsOption

WithEncOptsOmitStatistics sets omitStatistics in encOpts. omit statistics info

func WithEncOptsTruncate

func WithEncOptsTruncate(v int) EncOptsOption

WithEncOptsTruncate sets truncate in encOpts.

func WithEncOptsTruncateBytes

func WithEncOptsTruncateBytes(v int) EncOptsOption

WithEncOptsTruncateBytes sets truncateBytes in encOpts. truncate bytes to this length

func WithEncOptsTruncateBytesIfMoreThan added in v1.2.121

func WithEncOptsTruncateBytesIfMoreThan(v int) EncOptsOption

WithEncOptsTruncateBytesIfMoreThan sets truncateBytesIfMoreThan in encOpts. truncate bytes to this length if more than this length

func WithEncOptsTruncateMap

func WithEncOptsTruncateMap(v int) EncOptsOption

WithEncOptsTruncateMap sets truncateMap in encOpts. truncate map to this length

func WithEncOptsTruncateMapIfMoreThan added in v1.2.121

func WithEncOptsTruncateMapIfMoreThan(v int) EncOptsOption

WithEncOptsTruncateMapIfMoreThan sets truncateMapIfMoreThan in encOpts. truncate map to this length if more than this length

func WithEncOptsTruncateSliceOrArray added in v1.2.84

func WithEncOptsTruncateSliceOrArray(v int) EncOptsOption

WithEncOptsTruncateSliceOrArray sets truncateSliceOrArray in encOpts. truncate slice or array to this length

func WithEncOptsTruncateSliceOrArrayIfMoreThan added in v1.2.121

func WithEncOptsTruncateSliceOrArrayIfMoreThan(v int) EncOptsOption

WithEncOptsTruncateSliceOrArrayIfMoreThan sets truncateSliceOrArrayIfMoreThan in encOpts. truncate slice or array to this length if more than this length

func WithEncOptsTruncateString

func WithEncOptsTruncateString(v int) EncOptsOption

WithEncOptsTruncateString sets truncateString in encOpts. truncate string to this length

func WithEncOptsTruncateStringIfMoreThan added in v1.2.121

func WithEncOptsTruncateStringIfMoreThan(v int) EncOptsOption

WithEncOptsTruncateStringIfMoreThan sets truncateStringIfMoreThan in encOpts. truncate string to this length if more than this length

func WithEncOptsTruncateUrl added in v1.2.108

func WithEncOptsTruncateUrl(v bool) EncOptsOption

WithEncOptsTruncateUrl sets truncateUrl in encOpts. truncate query and fragment in url

type EncOptsOptionFunc

type EncOptsOptionFunc func(*encOpts)

EncOptsOptionFunc wraps a function that modifies encOpts into an implementation of the EncOptsOption interface.

type Encoder added in v1.2.84

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

An Encoder writes JSON values to an output stream.

func NewEncoder added in v1.2.84

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode added in v1.2.84

func (enc *Encoder) Encode(v any) error

Encode writes the JSON encoding of v to the stream, followed by a newline character.

See the documentation for Marshal for details about the conversion of Go values to JSON.

func (*Encoder) SetEscapeHTML added in v1.2.84

func (enc *Encoder) SetEscapeHTML(on bool)

SetEscapeHTML specifies whether problematic HTML characters should be escaped inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.

In non-HTML settings where the escaping interferes with the readability of the output, SetEscapeHTML(false) disables this behavior.

func (*Encoder) SetIndent added in v1.2.84

func (enc *Encoder) SetIndent(prefix, indent string)

SetIndent instructs the encoder to format each subsequent encoded value as if indented by the package-level function Indent(dst, src, prefix, indent). Calling SetIndent("", "") disables indentation.

func (*Encoder) SetTruncate added in v1.2.84

func (enc *Encoder) SetTruncate(n int)

SetTruncate shrinks bytes, string, map, slice, array 's len to n at most

type Marshaler added in v1.2.84

type Marshaler = json.Marshaler

Marshaler is the interface implemented by types that can marshal themselves into valid JSON.

type MarshalerError

type MarshalerError struct {
	Type reflect.Type
	Err  error
	// contains filtered or unexported fields
}

A MarshalerError represents an error from calling a [Marshaler.MarshalJSON] or encoding.TextMarshaler.MarshalText method.

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

func (*MarshalerError) Unwrap

func (e *MarshalerError) Unwrap() error

Unwrap returns the underlying error.

type Number

type Number = json.Number

A Number represents a JSON number literal.

type RawMessage added in v1.2.121

type RawMessage = json.RawMessage

type SyntaxError

type SyntaxError struct {
	Offset int64 // error occurred after reading Offset bytes
	// contains filtered or unexported fields
}

A SyntaxError is a description of a JSON syntax error. Unmarshal will return a SyntaxError if the JSON can't be parsed.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type UnsupportedTypeError

type UnsupportedTypeError = json.UnsupportedTypeError

An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.

type UnsupportedValueError

type UnsupportedValueError = json.UnsupportedValueError

An UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.

Jump to

Keyboard shortcuts

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