Skip to content

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.km

Source ​

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.km

Expected output:

text
{"guest":"Aki","temperature":42} true

Contract 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 guest and temperature.
  • json.Marshal is resolved from real Go export/type data.
  • Its ([]byte, error) result crosses into Result<string> only through explicit postfix ?.
  • string(encoded) validates UTF-8 and directly forwards Result<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.

Kinmokusei is a pre-1.0 project. Documentation describes implemented behavior.