How does EK9 handle JSON as a built-in type?
← JSON and Data Processing · Ref: Q188
JSON is a first-class built-in type in EK9. You create JSON values directly with constructors and the $$ operator, without importing external libraries.
JSON CONSTRUCTORS
Create JSON values from literals:
jsonNum <- JSON(42) jsonStr <- JSON("hello")
Create JSON objects with key-value pairs:
jsonObj <- JSON("name", JSON("Alice"))
NATURE CHECKS
JSON values have a nature you can query:
jsonObj.objectNature() checks if JSON object jsonArr.arrayNature() checks if JSON array jsonVal.valueNature() checks if JSON primitive
TO-JSON OPERATOR ($$)
The $$ operator converts any value to its JSON representation:
colour <- #FFAACC jsonColour <- $$ colour
This works with all built-in types.
STRING CONVERSION ($)
Convert JSON to its string form:
text <- $jsonObj
See Q189 for converting objects to JSON. See Q190 for parsing JSON strings. See Q191 for JSON with stream pipelines. See Q37 for String basics. See Q192 for JSON manipulate. See Q193 for JSON output.
Example
defines module qa.jsondata.firstclass defines program JsonFirstClassDemo() stdout <- Stdout() // === JSON CONSTRUCTORS === jsonNum <- JSON(42) stdout.println(`JSON number: ${jsonNum}`) jsonStr <- JSON("hello") stdout.println(`JSON string: ${jsonStr}`) // JSON object with key-value pair jsonObj <- JSON("name", JSON("Alice")) stdout.println(`JSON object: ${jsonObj}`) // === NATURE CHECKS === stdout.println(`Is object nature: ${jsonObj.objectNature()}`) stdout.println(`Is value nature: ${jsonNum.valueNature()}`) // === TO-JSON OPERATOR $$ === colour <- #FFAACC jsonColour <- $$ colour stdout.println(`Colour as JSON: ${jsonColour}`) anInt <- 99 jsonInt <- $$ anInt stdout.println(`Integer as JSON: ${jsonInt}`) // === STRING CONVERSION $ === text <- $jsonObj stdout.println(`JSON as string: ${text}`)
Common mistakes
E50060 — JSON constructor for key-value pairs requires both arguments to be JSON values. Passing a raw String as the value instead of JSON(String) triggers E50060 — constructor not resolved. Wrap the value with JSON(). See ek9 -h E50060 for details.
Incorrect:
jsonObj <- JSON("name", "Alice")
Correct:
jsonObj <- JSON("name", JSON("Alice"))
Other ways to ask this
- Is JSON a first-class type in EK9?
- How do I create JSON values in EK9?
- What JSON operations does EK9 support natively?
Coming from another language?
Java: JSON requires external libraries (Jackson, Gson). Python: json module in stdlib but returns dict/list. Rust: serde_json crate. Go: encoding/json package. Kotlin: kotlinx.serialization. EK9: JSON is a built-in type with constructors, operators, and stream integration. No imports needed.
Keywords: parse, array, serialize, first-class, built-in, constructor, data, type, object, json, nature, create