fn toJson
Canonical JSON text of x.
Example:
use std.ser { toJson }
data User { name: str; age: i32 }
fn main() io {
print(toJson(&User{ name: "ann", age: 31 })!)
}Output
{"name":"ann","age":31}Examples#
Serializing to JSON: any types without extra code.
What turns into JSON#
data, enum (as a string with the variant name), List, Map, T? (absent when none), nested records. 64-bit integers are written as strings.
use std.ser { toJson, fromJson }
enum Status { Active; Banned }
data Tag { key: str; value: str }
data Account {
id: i64
email: str
status: Status
score: f64
tags: List<Tag>
note: str?
limits: Map<str, i32>
}
fn main() io {
let acc = Account{ id: 5, email: "a@b.c", status: Status.Banned, score: 4.5, tags: [Tag{ key: "k", value: "v" }], note: "hi", limits: {"daily": 3} }
let text = toJson(&acc)!
print(text)
let back: Account = fromJson(&text)!
print("{back.status == Status.Banned} {back.note ?? "none"} {back.limits.get("daily") ?? 0} {back.tags[0].key}")
}Output
{"id":"5","email":"a@b.c","status":"Banned","score":4.5,"tags":[{"key":"k","value":"v"}],"note":"hi","limits":{"daily":3}}
true hi 3 kpub(api) fn toJson<T: Serializable>(x: &T) -> str | EncodeErrorSince. 1.0.0-beta
Parameters
| Name | Type |
|---|---|
x | &T |
Returns
str
Errors
EncodeError@error
Effects
none declared (pure unless the body says otherwise)
Defined in: std/ser/ser.oxl:2383