JSON and Serialization

32.1 json (Compile-Time, Fast)

import json

struct Address {
	city string
	zip  string @[json: 'postal_code']
}

struct User {
	name     string
	age      int
	email    string   @[omitempty]
	password string   @[json: '-']          // skip
	tags     []string
	address  Address
	nickname ?string                        // optional field
}

fn main() {
	u := User{name: 'Ana', age: 30, tags: ['admin'], address: Address{'Pune', '411001'}}
	s := json.encode(u)
	println(s)
	println(json.encode_pretty(u))
	decoded := json.decode(User, s) or { panic(err) }
	println(decoded.address.city)
	users := json.decode([]User, '[{"name":"Bo","age":20}]') or { [] }
	println(users.len)
	m := json.decode(map[string]int, '{"a":1,"b":2}') or { map[string]int{} }
	println(m)
}

32.2 x.json2 (Dynamic JSON)

import x.json2
raw := '{"name": "Ana", "scores": [1, 2, 3], "meta": {"active": true}}'
data := json2.decode[json2.Any](raw) or { panic(err) }
obj := data.as_map()
println(obj['name'] or { json2.Any('') }.str())
println(obj['scores'] or { json2.Any(0) }.arr().len)
println(json2.encode(obj))
// Typed decode with json2 (generic):
u := json2.decode[User](raw) or { User{} }
_ = u

32.3 Other Formats

toml (toml.parse_text, doc.value('server.port').int()), encoding.csv (csv.new_reader, read()), encoding.xml, encoding.base64, encoding.hex, encoding.binary, YAML via VPM packages.