Documentation ¶
Overview ¶
Flexible JSON formatter. Features:
- Preserves order.
- Fits dicts and lists on a single line until a certain width (configurable).
- Supports comments (configurable).
- Supports trailing commas (configurable).
- Fixes missing or broken punctuation.
- Tiny Go library + optional tiny CLI.
Current limitations:
- Always permissive. Unrecognized non-whitespace is treated as arbitrary content on par with strings, numbers, etc.
- Slower than `json.Indent` from the Go standard library.
- Input must be UTF-8.
Source and readme: https://github.com/mitranim/jsonfmt.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var Default = Conf{ Indent: ` `, Width: 80, CommentLine: `//`, CommentBlockStart: `/*`, CommentBlockEnd: `*/`, TrailingComma: false, StripComments: false, }
Default configuration. To override, make a copy:
conf := jsonfmt.Default conf.CommentLine = `#` content = jsonfmt.FormatBytes(conf, content)
See `Conf` for details.
Functions ¶
func FormatBytes ¶
Formats JSON text according to config, returning bytes.
func FormatString ¶
Formats JSON text according to config, returning a string.
func Unmarshal ¶
Shortcut that combines formatting with `json.Unmarshal`. Allows to decode JSON with comments or invalid punctuation, such as trailing commas. Slower than simply using `json.Unmarshal`. Avoid this when your input is guaranteed to be valid JSON, or when you should be enforcing valid JSON.
Types ¶
type Conf ¶
type Conf struct { Indent string `json:"indent"` Width uint64 `json:"width"` CommentLine string `json:"commentLine"` CommentBlockStart string `json:"commentBlockStart"` CommentBlockEnd string `json:"commentBlockEnd"` TrailingComma bool `json:"trailingComma"` StripComments bool `json:"stripComments"` }
Configuration passed to `Format`. See the variable `Default`.
`Indent` controls multi-line output. When empty, jsonfmt will not emit separator spaces or newlines, except at the end of single-line comments. To enforce single-line output, use `Indent: ""` and `StripComments: true`.
`Width` is the width limit for single-line formatting. If 0, jsonfmt will prefer multi-line mode. Note that `Indent` must be set for multi-line.
`CommentLine` starts a single-line comment. If empty, single-line comments won't be detected, and will be treated as arbitrary content surrounded by punctuation.
`CommentBlockStart` and `CommentBlockEnd` must both be set to work. If only one is set, the other is ignored. Nested block comments are supported. If unset, block comments will not be detected, and will be treated as arbitrary content surrounded by punctuation.
`TrailingComma` controls trailing commas for last elements in dicts and lists in multi-line mode. In single-line mode, trailing commas are always omitted.
`StripComments` omits all comments from the output. To enforce single-line mode, specify this together with `Indent: ""`. Otherwise, single-line comments are always followed by a newline.