Skip to content

class JSON::Builder
inherits Reference

A JSON builder generates valid JSON.

A JSON::Error is raised if attempting to generate an invalid JSON (for example, if invoking end_array without a matching start_array, or trying to use a non-string value as an object's field name).

Class methods

.new(io : IO)

Creates a JSON::Builder that will write to the given IO.

View source

Methods

#array

Writes the start of an array, invokes the block, and the writes the end of it.

View source

#bool(value : Bool)

Writes a boolean value.

View source

#document

View source

#end_array

Writes the end of an array.

View source

#end_document : Nil

Signals the end of a JSON document.

View source

#end_object

Writes the end of an object.

View source

#field

Writes an object's field and then invokes the block. This is equivalent of invoking string(value) and then invoking the block.

View source

#field(name, value)

Writes an object's field and value. The field's name is first converted to a String by invoking to_s on it.

View source

#flush

Flushes the underlying IO.

View source

#indent=(level : Int)

Sets the indent level (number of spaces).

View source

#indent=(string : String)

Sets the indent string.

View source

#max_nesting : Int32

By default the maximum nesting of arrays/objects is 99. Nesting more than this will result in a JSON::Error. Changing the value of this property allows more/less nesting.

View source

#max_nesting=(max_nesting)

By default the maximum nesting of arrays/objects is 99. Nesting more than this will result in a JSON::Error. Changing the value of this property allows more/less nesting.

View source

#next_is_object_key? : Bool

Returns true if the next thing that must pushed into this builder is an object key (so a string) or the end of an object.

View source

#null

Writes a null value.

View source

#number(number : Float)

Writes a float.

View source

#number(number : Int)

Writes an integer.

View source

#object

Writes the start of an object, invokes the block, and the writes the end of it.

View source

#raw(string : String)

Writes a raw value, considered a scalar, directly into the IO without processing. This is the only method that might lead to invalid JSON being generated, so you must be sure that string contains a valid JSON string.

View source

#scalar(value : Nil)

Writes a scalar value.

View source

#scalar(value : Bool)

Writes a scalar value.

View source

#scalar(value : Int | Float)

Writes a scalar value.

View source

#scalar(value : String)

Writes a scalar value.

View source

#start_array

Writes the start of an array.

View source

#start_document

Starts a document.

View source

#start_object

Writes the start of an object.

View source

#string(value)

Writes a string. The given value is first converted to a String by invoking to_s on it.

This method can also be used to write the name of an object field.

View source