jsonfmt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2023 License: Unlicense Imports: 5 Imported by: 1

README

Overview

Flexible JSON formatter. Features:

  • Preserves order.
  • Supports comments (configurable).
  • Supports trailing commas (configurable).
  • Supports max width (configurable).
    • For dicts and lists: single-line until given width, multi-line after exceeding said width.
  • Fixes missing or broken punctuation.
  • Tiny Go library.
  • Optional tiny CLI.
  • No dependencies.

See API documentation at https://godoc.org/github.com/mitranim/jsonfmt.

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.
  • Input and output are []byte, without streaming.
    • Streaming support could be added on demand.

Installation

Library

To use this as a library, simply import it:

import "github.com/mitranim/jsonfmt"

var formatted string = jsonfmt.Format[string](jsonfmt.Default, `{}`)
var formatted string = jsonfmt.FormatString(jsonfmt.Default, `{}`)
var formatted []byte = jsonfmt.FormatBytes(jsonfmt.Default, `{}`)

CLI

First, install Go: https://golang.org. Then run this:

go install github.com/mitranim/jsonfmt/jsonfmt@latest

This will compile the executable into $GOPATH/bin/jsonfmt. Make sure $GOPATH/bin is in your $PATH so the shell can discover the jsonfmt command. For example, my ~/.profile contains this:

export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin

Alternatively, you can run the executable using the full path. At the time of writing, ~/go is the default $GOPATH for Go installations. Some systems may have a different one.

~/go/bin/jsonfmt

Usage

See the library documentation on https://godoc.org/github.com/mitranim/jsonfmt.

For CLI usage, run jsonfmt -h.

Examples

Supports comments and trailing commas (all configurable):

{// Line comment
"one": "two", /* Block comment */ "three": 40}

Output:

{
  // Line comment
  "one": "two",
  /* Block comment */
  "three": 40,
}

Single-line until width limit (configurable):

{
  "one": {"two": ["three"], "four": ["five"]},
  "six": {"seven": ["eight"], "nine": ["ten"], "eleven": ["twelve"], "thirteen": ["fourteen"]}
}

Output:

{
  "one": {"two": ["three"], "four": ["five"]},
  "six": {
    "seven": ["eight"],
    "nine": ["ten"],
    "eleven": ["twelve"],
    "thirteen": ["fourteen"],
  },
}

Fix missing or broken punctuation:

{"one" "two" "three" {"four" "five"} "six" ["seven": "eight"]},,,

Output:

{"one": "two", "three": {"four": "five"}, "six": ["seven", "eight"]}

License

https://unlicense.org

Misc

I'm receptive to suggestions. If this library almost satisfies you but needs changes, open an issue or chat me up. Contacts: https://mitranim.com/#contacts

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

View Source
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 Format

func Format[Out, Src Text](conf Conf, src Src) Out

Formats JSON according to the config. See `Conf`.

func FormatBytes

func FormatBytes[Src Text](conf Conf, src Src) []byte

Formats JSON text according to config, returning bytes.

func FormatString

func FormatString[Src Text](conf Conf, src Src) string

Formats JSON text according to config, returning a string.

func Unmarshal

func Unmarshal[Src Text](src Src, out any) error

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.

type Text

type Text interface{ ~string | ~[]byte }

Describes various interchangeable text types.

Directories

Path Synopsis
Command line tool for jsonfmt.
Command line tool for jsonfmt.

Jump to

Keyboard shortcuts

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