module JSON::Tight

Overview

A JSON pretty-printer with a width budget. Each collection is rendered on a single line when it fits, in aligned columns when its elements are all individually short, or expanded one element per line when nothing tighter fits. Numbers are right-aligned within their column.

JSON::Tight.generate(JSON.parse(%([1,2,3]))) # => "[ 1, 2, 3 ]\n"
JSON::Tight.generate({"a" => 1, "b" => [2, 3]})
JSON::Tight.generate(json: %({"a":1}), width: 40)

The width budget applies to content only; leading indentation is not counted.

Defined in:

json-tight.cr

Constant Summary

DEFAULT_INDENT = 2

Spaces per nesting level in expanded layouts.

DEFAULT_WIDTH = 80

Width budget used when none is given.

VERSION = "1.0.0"

Class Method Summary

Class Method Detail

def self.generate(value : JSON::Any, width : Int32 = DEFAULT_WIDTH) : String #

Returns value formatted as a String ending in a newline.


[View source]
def self.generate(value, width : Int32 = DEFAULT_WIDTH) : String #

Returns value formatted as a String ending in a newline. value may be anything that responds to #to_json, including JSON::Serializable types and native collections.

NOTE A String here is treated as a JSON string scalar; to format a string of JSON, use the json: overload instead.


[View source]
def self.generate(io : IO, value : JSON::Any, width : Int32 = DEFAULT_WIDTH) : Nil #

Writes value to io, formatted and ending in a newline.


[View source]
def self.generate(io : IO, value, width : Int32 = DEFAULT_WIDTH) : Nil #

Writes value, which may be anything that responds to #to_json, to io, formatted and ending in a newline.


[View source]
def self.generate(io : IO, *, json : String, width : Int32 = DEFAULT_WIDTH) : Nil #

Parses json and writes it to io, reformatted and ending in a newline. Raises JSON::ParseException if json is not valid JSON.


[View source]
def self.generate(*, json : String, width : Int32 = DEFAULT_WIDTH) : String #

Parses json and returns it reformatted as a String ending in a newline. Raises JSON::ParseException if json is not valid JSON.


[View source]