JSON: Reading
● Intermediate3 min
json.parse gives a Json value; doc["key"] and doc[i] read into it, and .text(), .int() and the others give the value as an optional.
use std.json
fn main() ! Error {
const body = "\{\"user\": \{\"name\": \"asha\"}, \"tags\": [\"vip\", \"new\"]}"
const doc = try json.parse(body)
print(doc["user"]["name"].text() ?? "guest")
print(doc["user"]["email"].text() ?? "no email")
print(doc["tags"][0].text() ?? "none")
print(doc["tags"].len())
}The program ran and printed:
kavach run dynamic.kav
ashano emailvip2
- Reading never panics: a missing key, an index out of range, or reading into something that isn't an object gives
Null, so reads chain safely. - The method then gives
none, and??gives a fallback.
use std.json
fn main() ! Error {
const body = "\{\"name\": \"asha\", \"age\": 31, \"extra\": \{\"vip\": true}}"
const doc = try json.parse(body)
print(doc["name"].text() ?? "nobody")
print(doc["age"].int() ?? 0)
print(doc["extra"]["vip"].bool() ?? false)
print(doc["missing"]["deeper"].text() ?? "not there")
for (key, value) in doc.object() ?? [:] {
print("{key}: {value}")
}
}The program ran and printed:
kavach run unknown-fields.kav
asha31truenot therename: "asha"age: 31extra: {"vip":true}