How do I format JSON output in EK9?

← JSON and Data Processing · Ref: Q193

EK9 provides both compact and formatted JSON output. Use the $ operator for compact output and .prettyPrint() for human-readable formatted output.

COMPACT OUTPUT ($)

The $ string operator produces compact JSON:

  text <- $jsonObj

No extra whitespace, suitable for APIs and storage.

PRETTY PRINT

The .prettyPrint() method produces indented, readable JSON:

  formatted <- jsonObj.prettyPrint()

Useful for debugging, logging, and configuration files.

STRING INTERPOLATION

Use JSON values directly in string interpolation:

  stdout.println(`Data: ${jsonObj}`)

This calls the $ operator automatically.

See Q188 for JSON as a first-class type. See Q43 for string interpolation.

Example

defines module qa.jsondata.output

  defines program

    JsonOutputDemo()
      stdout <- Stdout()

      jsonData <- JSON(`{"name": "Alice", "age": 30, "active": true}`)

      // === COMPACT OUTPUT WITH $ ===

      compact <- $jsonData
      stdout.println("Compact: " + compact)

      // === PRETTY PRINT ===

      formatted <- jsonData.prettyPrint()
      stdout.println("Formatted:")
      stdout.println(formatted)

      // === STRING INTERPOLATION ===

      stdout.println(`Interpolated: ${jsonData}`)

      // === NESTED JSON ===

      nested <- JSON(`{"person": {"name": "Bob", "scores": [90, 85, 92]}}`)
      stdout.println("Nested compact: " + $nested)
      stdout.println("Nested formatted:")
      stdout.println(nested.prettyPrint())

Common mistakes

E50060 — The JSON type does not have a 'toString()' method. Use the '$' operator for compact string conversion and '.prettyPrint()' for formatted output. EK9 uses operator syntax, not Java-style method calls. See ek9 -h E50060 for details.

Incorrect:

compact <- jsonData.toString()

Correct:

compact <- $jsonData
Other ways to ask this
  • How do I pretty print JSON in EK9?
  • How do I get readable JSON output in EK9?
  • What is the difference between compact and formatted JSON in EK9?

Coming from another language?

Java: Jackson ObjectMapper.writerWithDefaultPrettyPrinter(). Python: json.dumps(indent=2). Rust: serde_json::to_string_pretty(). Go: json.MarshalIndent(). Kotlin: Json { prettyPrint = true }. EK9: .prettyPrint() method on JSON type, $ operator for compact form.

Keywords: json, readable, string, display, print, data, output, compact, pretty, serialize, format