OxL Reference

fn fromJson

Decodes canonical JSON text.

Example:

oxl✓ checked in CI
use std.ser { fromJson }

data User { name: str; age: i32 }

fn main() io {
  let u: User = fromJson(&"{{\"name\":\"bob\",\"age\":25}}")!
  print("{u.name} {u.age}")
}
Output
bob 25

Examples#

Parsing JSON with type and refinement checks.

Strict parsing#

A missing field without a default, a wrong type, a value outside a refined type's range and bad syntax give DecodeError; a field with a default may be omitted.

oxl✓ checked in CI
use std.ser { fromJson }

type Port = u16 where 1..=65535
data Server { host: str; port: Port; tls: bool = false }  // the field has a default value

fn load(text: str) -> str {
  match fromJson<Server>(&text) {
    Server s => "ok {s.host}:{s.port} tls={s.tls}"
    DecodeError => "invalid"
  }
}

fn main() io {
  print(load("{{\"host\":\"a\",\"port\":8080}}"))
  print(load("{{\"host\":\"a\",\"port\":8080,\"tls\":true}}"))
  print(load("{{\"host\":\"a\",\"port\":0}}"))  // the refined type rejects 0 while decoding
  print(load("{{\"host\":\"a\",\"port\":70000}}"))
  print(load("{{\"port\":80}}"))
  print(load("[]"))
}
Output
ok a:8080 tls=false
ok a:8080 tls=true
invalid
invalid
invalid
invalid
pub(api) fn fromJson<T: Serializable>(s: &str) -> T | DecodeError

Since. 1.0.0-beta

Parameters

NameType
s&str

Returns

T

Errors

Effects

none declared (pure unless the body says otherwise)

Defined in: std/ser/ser.oxl:2407

See also

OxL 1.0.0-beta · Documentation version 1.0.0-beta© OxwaldLink · generated from the Standard, the std sources and the guides