JSON Serialization
to_json() and from_json() for data serialization.
Example 028 of the basic Soma programs: a small, commented program that teaches one thing. Every output below was printed by soma 3.2.4 when this page was built.
How it is built
The cell JsonRoundtrip has no face and no memory. Handlers: run (line 15).
The source
028_json_roundtrip.cell
// ============================================================================
// 028 — JSON Serialization
// ============================================================================
// to_json() and from_json() for data serialization.
//
// Run: soma run 028_json_roundtrip.cell run
// Expect:
// json: {"name": "Alice", "scores": [95, 87, 92]}
// parsed name: Alice
// parsed scores: [95, 87, 92]
// list json: [{"id": 1, "v": "a"}, {"id": 2, "v": "b"}]
cell JsonRoundtrip {
on run() {
// Serialize a map to JSON
let data = map("name", "Alice", "scores", list(95, 87, 92))
let json = to_json(data)
print("json: {json}")
// Parse JSON back to a map
let parsed = from_json(json)
print("parsed name: {parsed.name}")
print("parsed scores: {parsed.scores}")
// Serialize a list of maps
let items = list(
map("id", 1, "v", "a"),
map("id", 2, "v", "b")
)
let items_json = to_json(items)
print("list json: {items_json}")
return "done"
}
}What the toolchain says
$ soma check 028_json_roundtrip.cell
✓ All checks passed.$ soma run 028_json_roundtrip.cell run
json: {"name":"Alice","scores":[95,87,92]}
parsed name: Alice
parsed scores: [95, 87, 92]
list json: [{"id":1,"v":"a"},{"id":2,"v":"b"}]
done