How do I parse a JSON string in EK9?

← JSON and Data Processing · Ref: Q190

Pass a JSON string to the JSON constructor to parse it. Access properties with .get(key) for objects and .get(index) for arrays. Iterate with .iterator().

PARSING JSON STRINGS

Pass a JSON-formatted string to the JSON constructor:

  data <- JSON(`{"name": "Alice", "age": 30}`)

ACCESSING PROPERTIES

Use .get(key) to access object properties:

  name <- parsed.get("name")

Use .get(index) to access array elements:

  first <- jsonArray.get(0)

NATURE CHECKS

Check what kind of JSON value you have:

  parsed.objectNature()  true for JSON objects
  parsed.arrayNature()   true for JSON arrays
  parsed.valueNature()   true for primitives

ITERATION

Iterate over JSON arrays or object entries:

  for item in parsed.iterator()
    stdout.println($item)

See Q188 for JSON as a first-class type. See Q48 for Result type. See Q29 for unset variables.

Example

defines module qa.jsonparsed.parsing

  defines program

    JsonParsingDemo()
      stdout <- Stdout()

      // === PARSING JSON STRINGS ===

      parsed <- JSON(`{"name": "Alice", "age": 30}`)
      stdout.println(`Parsed JSON: ${parsed}`)

      // === ACCESSING PROPERTIES ===

      nameJson <- parsed.get("name")
      stdout.println(`Name: ${nameJson}`)

      ageJson <- parsed.get("age")
      stdout.println(`Age: ${ageJson}`)

      // === NATURE CHECKS ===

      stdout.println(`Is object: ${parsed.objectNature()}`)
      stdout.println(`Is value: ${parsed.valueNature()}`)

      // === JSON ARRAYS ===

      arr <- JSON(`[10, 20, 30]`)
      stdout.println(`Array: ${arr}`)
      stdout.println(`Is array: ${arr.arrayNature()}`)

      firstItem <- arr.get(0)
      stdout.println(`First item: ${firstItem}`)

      // === ITERATION ===

      for item in arr.iterator()
        stdout.println(`Item: ${item}`)

Common mistakes

E50060 — The JSON type does not have 'getString()', 'getInt()', or similar typed accessor methods. Use '.get(key)' for object properties and '.get(index)' for array elements. The result is always a JSON value. See ek9 -h E50060 for details.

Incorrect:

nameJson <- parsed.getString("name")

Correct:

nameJson <- parsed.get("name")
Other ways to ask this
  • How do I create JSON from a string in EK9?
  • How do I access JSON properties in EK9?
  • How do I read JSON data in EK9?

Coming from another language?

Java: Jackson ObjectMapper.readTree() for tree model, readValue() for POJO binding. Python: json.loads() to dict. Rust: serde_json::from_str(). Go: json.Unmarshal(). Kotlin: kotlinx.serialization Json.decodeFromString(). EK9: JSON constructor parses strings directly, .get() for property access, .iterator() for traversal.

Keywords: access, property, null, parse, get, json, serialize, ok, guard, error, iterate, result, string, data