prettyjson

package
v1.2.115 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2024 License: MIT Imports: 17 Imported by: 0

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
		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": "while"},
		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)

}
Output:

{"ID":1,"Name":"Reds","LongName":"The quick ...43 chars","Colors":["The quick ...43 chars","Crimson", "...5 elems"],"ColorById":{"0":"red","1":"green","...4 pairs":"4"},"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 WithEncOptsOmitEmpty added in v1.2.112

func WithEncOptsOmitEmpty(v bool) EncOptsOption

WithEncOptsOmitEmpty sets omitEmpty in encOpts.

func WithEncOptsQuoted

func WithEncOptsQuoted(v bool) EncOptsOption

WithEncOptsQuoted sets quoted in encOpts. quoted causes primitive fields to be encoded inside JSON strings.

func WithEncOptsTruncate

func WithEncOptsTruncate(v int) EncOptsOption

WithEncOptsTruncate sets truncate in encOpts.

func WithEncOptsTruncateBytes

func WithEncOptsTruncateBytes(v int) EncOptsOption

WithEncOptsTruncateBytes sets truncateBytes in encOpts.

func WithEncOptsTruncateMap

func WithEncOptsTruncateMap(v int) EncOptsOption

WithEncOptsTruncateMap sets truncateMap in encOpts.

func WithEncOptsTruncateSliceOrArray added in v1.2.84

func WithEncOptsTruncateSliceOrArray(v int) EncOptsOption

WithEncOptsTruncateSliceOrArray sets truncateSliceOrArray in encOpts.

func WithEncOptsTruncateString

func WithEncOptsTruncateString(v int) EncOptsOption

WithEncOptsTruncateString sets truncateString in encOpts.

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 = json.MarshalerError

A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.

type Number

type Number = json.Number

A Number represents a JSON number literal.

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