parsed_it/json
JSON parsing and serialization for Gleam.
This module provides functions for parsing JSON strings into Gleam values and serializing Gleam values to JSON strings.
Parsing JSON
Use parse with a decoder for type-safe parsing:
import gleam/dynamic/decode
import parsed_it/json
type User {
User(name: String, age: Int)
}
fn user_decoder() -> decode.Decoder(User) {
use name <- decode.field("name", decode.string)
use age <- decode.field("age", decode.int)
decode.success(User(name:, age:))
}
pub fn example() {
json.parse(from: "{\"name\":\"Lucy\",\"age\":30}", using: user_decoder())
}
Use parse_dynamic when you need to inspect raw JSON structure:
let result = json.parse_dynamic(from: json_string)
Building JSON
Use the constructor functions to build JSON values:
json.object([
#("name", json.string("Lucy")),
#("scores", json.array([json.int(95), json.int(87)])),
#("active", json.bool(True)),
])
|> json.to_string
Error Handling
Parse errors are returned as JsonDecodeError variants:
UnexpectedEnd- JSON input was truncatedUnexpectedChar(String)- Invalid character encountered (hex code)UnexpectedSequence(String)- Invalid token sequenceUnableToDecode(List(DecodeError))- Valid JSON but wrong shape for decoder
Platform Notes
Erlang: Uses OTP’s built-in json module.
JavaScript: Uses native JSON.parse/JSON.stringify. Error details
vary by JavaScript engine; some engines may return empty error information.
Types
An opaque type representing a JSON value.
This type is used for building JSON structures that can be serialized
to strings. Use the constructor functions like string, int, bool,
array, and object to create JSON values.
pub type Json
Errors that can occur when parsing JSON.
Note: This is a public ADT, so adding new variants would be a breaking change. Pattern matching on these variants is safe and exhaustive.
The UnexpectedChar variant contains a hex representation of the byte
(e.g., “0x7B” for ‘{’) when it can be determined from the error.
pub type JsonDecodeError {
UnexpectedEnd
UnexpectedChar(String)
UnexpectedSequence(String)
UnableToDecode(List(decode.DecodeError))
}
Constructors
-
UnexpectedEndThe JSON input ended unexpectedly before a complete value was parsed. This typically indicates truncated input or unclosed brackets/quotes.
-
UnexpectedChar(String)An unexpected character was encountered during parsing. The string contains the hex code of the character (e.g., “0x7B”). May be empty if the JavaScript engine doesn’t provide error details.
-
UnexpectedSequence(String)An unexpected sequence of characters was encountered during parsing. For example, an unquoted identifier where a string was expected.
-
UnableToDecode(List(decode.DecodeError))The JSON was valid but could not be decoded into the expected type. Contains the list of decode errors explaining what went wrong.
Values
pub fn object(entries: List(#(String, Json))) -> Json
Creates a JSON object from a list of key-value pairs.
pub fn parse(
from json: String,
using decoder: decode.Decoder(t),
) -> Result(t, JsonDecodeError)
Parses a JSON string and decodes it using the provided decoder.
Returns an error if the JSON is invalid or if the decoded value doesn’t match the expected type.
pub fn parse_dynamic(
from json: String,
) -> Result(dynamic.Dynamic, JsonDecodeError)
Parses a JSON string into a Dynamic value without decoding.
This is useful when you want to inspect the raw JSON structure before deciding how to decode it, or when building generic JSON processing tools.
Example
let result = json.parse_dynamic(from: "{\"key\": \"value\"}")
// result contains the raw dynamic structure
pub fn to_string(json: Json) -> String
Converts a JSON value to its string representation.
pub fn to_string_tree(json: Json) -> string_tree.StringTree
Converts a JSON value to a StringTree representation.
This is useful for efficiently building larger strings or for streaming output without intermediate string allocations.
Example
let tree = json.object([#("key", json.string("value"))])
|> json.to_string_tree
Note: Currently this is implemented as to_string followed by
conversion to StringTree. A future version may provide a more efficient
streaming implementation.