gleam/json

Types

pub type DecodeError {
  UnexpectedEndOfInput
  UnexpectedByte(byte: String, position: Int)
  UnexpectedSequence(byte: String, position: Int)
}

Constructors

  • UnexpectedEndOfInput
  • UnexpectedByte(byte: String, position: Int)
  • UnexpectedSequence(byte: String, position: Int)
pub external type Json

Functions

pub fn array(
  from entries: List(a),
  of inner_type: fn(a) -> Json,
) -> Json

Encode a list into a JSON array.

Examples

> to_string(array([1, 2, 3], of: int))
"[1, 2, 3]"
pub external fn bool(input: Bool) -> Json

Encode a bool into JSON.

Examples

> to_string(bool(False))
"false"
pub external fn decode(String) -> Result(Dynamic, DecodeError)

Decode a JSON string into dynamically typed data which can be decoded into typed data with the gleam/dynamic module.

Examples

> decode("[1,2,3]")
Ok(dynamic.from([1, 2, 3]))
> decode("[")
Error(UnexpectedEndOfInput)
pub external fn float(input: Float) -> Json

Encode an float into JSON.

Examples

> to_string(float(4.7))
"4.7"
pub external fn int(input: Int) -> Json

Encode an int into JSON.

Examples

> to_string(int(50))
"50"
pub external fn null() -> Json

The JSON value null.

Examples

> to_string(null())
"null"
pub fn nullable(
  from input: Option(a),
  of inner_type: fn(a) -> Json,
) -> Json

Encode an optional value into JSON, using null if it the None variant.

Examples

> to_string(nullable(Some(50), of: int))
"50"
> to_string(nullable(None, of: int))
"null"
pub external fn object(entries: List(#(String, Json))) -> Json

Encode a list of key-value pairs into a JSON object.

Examples

> to_string(object([
  #("game", string("Pac-Man")),
  #("score", int(3333360)),
]))
"{\"game\":\"Pac-Mac\",\"score\":3333360}"
pub external fn preprocessed_array(from: List(Json)) -> Json

Encode a list of JSON values into a JSON array.

Examples

> to_string(preprocessed_array([int(1), float(2.0), string("3")]))
"[1, 2.0, \"3\"]"
pub external fn string(input: String) -> Json

Encode a string into JSON, using normal JSON escaping.

Examples

> to_string("Hello!")
"\"Hello!\""
pub external fn to_string(Json) -> String

Convert a JSON value into a string.

Where possible prefer the to_string_builder function as it is faster than this function, and BEAM VM IO is optimised for sending StringBuilder data.

Examples

> to_string(array([1, 2, 3], of: int))
"[1,2,3]"
pub external fn to_string_builder(Json) -> StringBuilder

Convert a JSON value into a string builder.

Where possible prefer this function to the to_string function as it is slower than this function, and BEAM VM IO is optimised for sending StringBuilder data.

Examples

> to_string_builder(array([1, 2, 3], of: int))
string_builder.from_string("[1,2,3]")