Encode JSON with a Go package
This recipe uses a structural object as a data-transfer value and calls the real Go encoding/json package.
Project tree
text
json-value/
└── main.kmSource
ts
import go json from "encoding/json";
import go fmt from "fmt";
function encodeVisit(): Result<string> {
const payload: { guest: string, temperature: int } = {
guest: "Aki",
temperature: 42,
};
const encoded = json.Marshal(payload)?;
return string(encoded);
}
function main(): void {
const [text, err] = encodeVisit();
fmt.Println(text, err === nil);
}Run
sh
keika check main.km
keika run main.kmExpected output:
text
{"guest":"Aki","temperature":42} trueContract demonstrated
- The structural object type supplies an exact expected shape for the literal.
- Generated anonymous Go fields are public and receive deterministic JSON tags preserving
guestandtemperature. json.Marshalis resolved from real Go export/type data.- Its
([]byte, error)result crosses intoResult<string>only through explicit postfix?. string(encoded)validates UTF-8 and directly forwardsResult<string>.
For a complete server using direct net/http and encoding/json, see the repository's JSON API source.
Decode into a domain class
JSON decoding is not a call to a Kinmokusei constructor or setter. Public-field updates and newly allocated nested values retain Go's decoding behavior; a successful decode does not prove application invariants. Decode a DTO, validate it, then construct the class. The class-input recipe shows that boundary with an executable example and the current target-type limitations.