json
Import json to exchange data with JSON APIs and files. marshal(value, indent=0) produces JSON text; unmarshal(data) parses JSON text (str or Bytes) into Goblin values.
import "json"
var text = json.marshal({"name": "Ada", "scores": [90, 95]})
var user = json.unmarshal(text)
print(user["name"])
print(user["scores"][0])
Objects become dictionaries, arrays become lists, JSON numbers become Int or Float, and JSON null becomes nil. Pass a positive indent to marshal for readable output.
print(json.marshal({"ok": true}, 2))
unmarshal raises ParseError for invalid JSON. Catch it when parsing external input.
Values and formatting
marshal accepts every standard Goblin value that has a JSON equivalent: dictionaries, lists, strings, integers, floats, booleans, and nil. Dictionary keys must be strings and are encoded as JSON object keys in sorted order, so the output is deterministic; a non-string key raises TypeError. The optional indent argument controls pretty printing; omit it for compact data sent over a network.
var payload = {
"name": "Ada",
"tags": ["math", "logic"],
"enabled": true,
"note": nil
}
print(json.marshal(payload, 2))
When decoding, inspect the resulting values with ordinary list and dictionary operations. A JSON integer becomes Int while a decimal number becomes Float.
Encoding your own types
A user type takes part in marshal by implementing the module's ToJSON trait.
Its one method, to_json(self), returns the value to encode in the instance's
place, which may itself contain other ToJSON values. An empty impl encodes the
fields as a JSON object keyed by field name. marshal raises TypeError for a user
type without the impl.
type Point(x, y) {
impl json.ToJSON {}
}
type Celsius(degrees) {
impl json.ToJSON {
func to_json(self) {
return Str(self.degrees) + "C"
}
}
}
print(json.marshal({"at": Point(1, 2), "temp": Celsius(21)}))
# {"at":{"x":1,"y":2},"temp":"21C"}
Handling untrusted input
JSON from a file or HTTP response is external input. Keep parsing and validation separate: first catch malformed JSON, then verify the fields your program requires.
try {
var config = json.unmarshal("{\"port\": 8080}")
var port = config.get("port", default=8080)
print(port)
} catch err {
if err.is(ParseError) {
print("configuration is not valid JSON")
} else {
raise err
}
}