Helpers for Go’s encoding/json package.
go get github.com/solsw/jsonhelper
import "github.com/solsw/jsonhelper"
The package provides convenience wrappers around json.Indent
and json.MarshalIndent that operate on
io.Reader/io.Writer, strings, and arbitrary values, plus a set of Default* variants
that apply a package-wide default prefix and indent.
For the meaning of the prefix and indent arguments, see the
json.Indent documentation.
These take explicit prefix and indent arguments.
| Function | Description |
|---|---|
IndentRW(r io.Reader, w io.Writer, prefix, indent string) error |
Reads JSON from r and writes indented JSON to w. |
IndentStr(j, prefix, indent string) (string, error) |
Returns the indented form of JSON string j. |
IndentAny(v any, prefix, indent string) (string, error) |
Returns the indented JSON encoding of v as a string. |
These use the package variables DefaultPrefix and DefaultIndent.
| Variable | Default value |
|---|---|
DefaultPrefix |
"" |
DefaultIndent |
" " (four spaces) |
Set them once at program startup, before first use, if you need different values.
| Function | Description |
|---|---|
DefaultRW(r io.Reader, w io.Writer) error |
Like IndentRW using the default prefix and indent. |
DefaultStr(j string) (string, error) |
Like IndentStr using the default prefix and indent. |
DefaultAny(v any) (string, error) |
Like IndentAny using the default prefix and indent. |
Indent a JSON string:
out, err := jsonhelper.IndentStr(`{"name":"Go","year":2009}`, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
// {
// "name": "Go",
// "year": 2009
// }
Indent an arbitrary value:
v := map[string]any{"name": "Go", "year": 2009}
out, err := jsonhelper.DefaultAny(v)
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
Reader to writer:
if err := jsonhelper.DefaultRW(os.Stdin, os.Stdout); err != nil {
log.Fatal(err)
}