std.json

JSON: reading JSON text into values, and writing values as JSON text.

import std.json

let value: json.Json = json.parse("{\"name\": \"Ada\", \"tags\": [\"x\"]}")?
match value.get("name") {
    Some(name) => print(json.stringify(name))
    None => print("no name")
}
let reply: json.Json = json.object(["ok": json.from_bool(true)])
print(json.stringify(reply))     // {"ok":true}

Numbers are kept as they are written (42, -1.5e3), so none loses precision; as_int reads whole numbers and as_float any number.

Types

enum Json

pub enum Json {
    Null,
    Bool(bool),
    Number(string),
    Str(string),
    Array(List[Json]),
    Object(Map[string, Json]),
}

A JSON value.

Number

A number, as written in the JSON text.

Object

Members keep the order of the text; a repeated key keeps its last value.

Methods

pub fn get(self, key: string) -> Option[Json]

A member of an object.

pub fn at(self, index: i64) -> Option[Json]

An element of an array.

pub fn as_string(self) -> Option[string]
pub fn as_int(self) -> Option[i64]

A whole number; None for other values and for numbers with a fraction or exponent.

pub fn as_float(self) -> Option[f64]

Any number, as the nearest f64.

pub fn as_bool(self) -> Option[bool]
pub fn as_array(self) -> Option[List[Json]]
pub fn as_object(self) -> Option[Map[string, Json]]
pub fn is_null(self) -> bool
pub fn kind(self) -> string

"null", "bool", "number", "string", "array" or "object".

Functions

fn null

pub fn null() -> Json

fn from_bool

pub fn from_bool(value: bool) -> Json

fn from_int

pub fn from_int(value: i64) -> Json

fn from_float

pub fn from_float(value: f64) -> Json

A number; NaN and infinities, which JSON cannot hold, become null.

fn from_string

pub fn from_string(value: string) -> Json

fn array

pub fn array(items: List[Json]) -> Json

fn object

pub fn object(members: Map[string, Json]) -> Json

fn stringify

pub fn stringify(value: Json) -> string

The value as compact JSON text.

fn pretty

pub fn pretty(value: Json) -> string

The value as JSON text indented by two spaces per level.

fn quote

pub fn quote(text: string) -> string

A JSON string literal.

fn encode

pub fn encode[T: Data](value: T) -> string

A value as compact JSON text.

fn to_json

pub fn to_json[T: Data](value: T) -> Json

A value as a Json.

fn decode

pub fn decode[T: Data](text: string) -> Result[T, string]

A value of type T from JSON text.

fn from_json

pub fn from_json[T: Data](value: Json) -> Result[T, string]

A value of type T from a Json.

fn parse

pub fn parse(text: string) -> Result[Json, string]

Parses JSON text. Errors say what is wrong and where, counting characters from 1: "expected ':' at character 9".