gleam_json

repository·main·Indexed 41 days ago

https://github.com/gleam-lang/json

A Gleam library for encoding and parsing JSON data. Provides the `gleam/json` module to convert Gleam data structures into JSON strings via `json.to_string` and parse JSON strings back into Gleam types using `json.parse` and decoders from the `gleam/dynamic/decode` module.

Tokens
654
Snippets
3
Records
3
Agent score
50%

What's inside Gleam JSON

  1. Parse JSON strings into Gleam types

    main

    To convert a JSON string back into a Gleam type, use json.parse.

    Parsing works in two steps:

    1. Define a decoder: Use the gleam/dynamic/decode module from the Gleam standard library to define how fields in the JSON should map to your Gleam type (e.g., using decode.field).
    2. Execute parsing: Pass the JSON string and your decoder to json.parse.

    json.parse returns a Result(T, json.DecodeError), where T is your target type.

    import myapp.{type Cat, Cat}
    import gleam/json
    import gleam/dynamic/decode
    
    pub fn cat_from_json(json_string: String) -> Result(Cat, json.DecodeError) {
      let cat_decoder = {
        use name <- decode.field("name", decode.string)
        use lives <- decode.field("lives", decode.int)
        use nicknames <- decode.field("nicknames", decode.list(decode.string))
        decode.success(Cat(name:, lives:, nicknames:))
      }
      json.parse(from: json_string, using: cat_decoder)
    }
  2. Encode Gleam data to JSON strings

    main

    To convert Gleam data structures into JSON, use the gleam/json module. You build a JSON object using json.object and populate its fields with specific JSON types like json.string, json.int, json.null, or json.array. Once the object is constructed, call json.to_string to produce the final JSON string.

    Note that json.array requires an of: argument specifying the type of elements in the array.

    import myapp.{type Cat}
    import gleam/json
    
    pub fn cat_to_json(cat: Cat) -> String {
      json.object([
        #("name", json.string(cat.name)),
        #("lives", json.int(cat.lives)),
        #("flaws", json.null()),
        #("nicknames", json.array(cat.nicknames, of: json.string)),
      ])
      |> json.to_string
    }