How do I convert an EK9 object to JSON?
← JSON and Data Processing · Ref: Q189
EK9 uses the $$ (to-JSON) operator to convert values to JSON. Records with 'default operator $$' automatically serialize all fields to a JSON object.
TO-JSON ON BUILT-IN TYPES
All built-in types support $$:
jsonInt <- $$ 42 jsonStr <- $$ "hello" jsonBool <- $$ true
TO-JSON ON RECORDS
Records with 'default operator $$' serialize all fields:
defines record Person name as String: String() age as Integer: Integer() default operator $$
Then: jsonPerson <- $$ person
The result is a JSON object with properties for each field.
UNSET FIELDS
Unset fields in a record become JSON null values. EK9's tri-state model maps naturally to JSON:
set value maps to JSON value unset value maps to JSON null absent value maps to JSON null
See Q188 for JSON as a first-class type. See Q97 for records. See Q29 for unset variables.
Example
defines module qa.jsondata.tojson defines record Person name as String: String() age as Integer: Integer() Person() -> n as String a as Integer name: n age: a default operator ? default operator $$ defines program JsonToJsonDemo() stdout <- Stdout() // === $$ ON BUILT-IN TYPES === jsonInt <- $$ 42 stdout.println(`Integer as JSON: ${jsonInt}`) jsonStr <- $$ "hello" stdout.println(`String as JSON: ${jsonStr}`) jsonBool <- $$ true stdout.println(`Boolean as JSON: ${jsonBool}`) // === $$ ON RECORDS === person <- Person("Alice", 30) jsonPerson <- $$ person stdout.println(`Person as JSON: ${jsonPerson}`) // === UNSET FIELDS BECOME NULL === partial <- Person() jsonPartial <- $$ partial stdout.println(`Partial person JSON: ${jsonPartial}`)
Common mistakes
E08180 — Record fields must be initialized inline with a default value. Declaring a field without an initializer triggers E08180. Use 'String()' for an unset default or provide a literal default value. See ek9 -h E08180 for details.
Incorrect:
name as String
Correct:
name as String: String()
E50060 — EK9 types do not have a 'toJSON()' method. Use the $$ operator to convert any value to its JSON representation. For records, 'default operator $$' auto-generates JSON serialization of all fields. See ek9 -h E50060 for details.
Incorrect:
jsonPerson <- person.toJSON()
Correct:
jsonPerson <- $$ person
Other ways to ask this
- How does the $$ operator work for JSON serialization?
- How do I serialize a record to JSON in EK9?
- How do I convert EK9 values to JSON format?
Coming from another language?
Java: Jackson @JsonSerialize or Gson.toJson() for serialization. Python: json.dumps() with custom encoder. Rust: serde_json::to_string(). Go: json.Marshal(). Kotlin: kotlinx.serialization @Serializable. EK9: 'default operator $$' on records for automatic JSON serialization, $$ operator on any value.
Keywords: unset, field, class, convert, null, serialize, operator, record, json, data