JSON Module (Headless)

JSON Module (Headless)

Headless (no GUI) example demonstrating every function in the json module. Uses only the core package — no Fyne/GUI dependencies.

Features

  • json.parse(text) - Decode a JSON string into Risor values (maps, lists, scalars)
  • json.marshal(obj) - Encode a Risor value to a compact JSON string
  • json.marshal_indent(obj) - Pretty-printed JSON (default 2-space indent)
  • json.marshal_indent(obj, " ") - Pretty-printed with a custom indent
  • json.valid(text) - Report whether a string is valid JSON
  • json.write(path, obj, indent?) / json.read(path) - File round-trip

Code

require(["v0.8", "@json"])

// json.parse — decode a JSON string into Risor values
let user = json.parse(`{"name": "Ada", "age": 36, "admin": true, "tags": ["x", "y"]}`)
print("  name  = " + user["name"])
print("  admin = " + string(user["admin"]))

// json.marshal — compact JSON string
let record = {id: 1, items: ["pen", "paper"], nested: {ok: true}}
print(json.marshal(record))

// json.marshal_indent — pretty-printed (default 2-space, or custom indent)
print(json.marshal_indent(record))
print(json.marshal_indent(record, "    "))

// json.valid — check whether a string is valid JSON
print(json.valid(`{"a": 1}`))   // true
print(json.valid("{bad"))        // false

// json.write then json.read — round-trip through a file
let path = "record-out.json"
json.write(path, record, "  ")   // optional indent -> pretty file
let reloaded = json.read(path)
print("  reloaded.nested.ok = " + string(reloaded["nested"]["ok"]))

Enable the module in the Go host with core.WithJSON() and declare it in scripts with require(["@json"]).

Running

cd examples/39-json-headless
go run main.go

The file round-trip writes record-out.json in the current directory.

Full Source

View full example on GitHub ↗