AutolangDocs
std/json

JSON

The std/json module provides high-performance, memory-safe JSON processing. Autolang supports parsing text payloads, dynamic object construction via indexing, safe field access, and two-way mapping directly to statically typed data transfer objects (DTOs).

Parsing & Instantiation

Parse JSON strings using the static method Json.parse() or the string extension parseJson(). JSON objects can also be constructed dynamically using bracket indexing obj[key].

@import("std/json") // 1. Parse JSON string val rawJson = "{\"orderId\": \"PO-9912\", \"total\": 1250.5, \"approved\": true}" val payload = Json.parse(rawJson) println("Is object: " + payload.isObject()) // true println("Order ID: " + payload.get("orderId").asString()) // PO-9912 // 2. Parse using string extension val quickObj = "{\"department\": \"Finance\", \"level\": 3}".parseJson() println("Department: " + quickObj.getString("department")) // Finance println("Level: " + quickObj.getInt("level")) // 3 // 3. Build dynamic JSON object via bracket indexing [] val invoice = Json.emptyObject() invoice["invoiceNo"] = Json.fromString("INV-2026-001") invoice["amount"] = Json.fromFloat(450.75) invoice["isSettled"] = Json.fromBool(false) println("Invoice No: " + invoice["invoiceNo"].asString()) // INV-2026-001 println("Invoice size: " + invoice.getSize())

Convenience Accessors & Default Fallbacks

To eliminate manual type verification, Autolang provides typed getters like getString() and getInt(), alongside safe variants optString() and optInt() that supply default fallbacks when keys are absent.

@import("std/json") val data = "{\"code\": \"HQ-01\", \"retryCount\": 2}".parseJson() // Direct extraction val code = data.getString("code") val retries = data.getInt("retryCount") // Safe extraction with default fallback val timeout = data.optInt("timeoutMs", 5000) val note = data.optString("note", "No note provided") println("Timeout: " + timeout) // 5000 println("Note: " + note)

JSON Arrays & Typed Conversions

Construct JSON arrays using Json.emptyArray() and convert them directly into native Autolang typed arrays using toIntArray(), toFloatArray(), or toStringArray().

@import("std/json") val jsonArr = Json.parse("[100, 200, 300]") println("Is array: " + jsonArr.isArray()) // true println("Array size: " + jsonArr.getSize()) // 3 println("First item: " + jsonArr.getAt(0).asInt()) // 100 // Convert to typed integer array val integerList = jsonArr.toIntArray() println("Integer list size: " + integerList.size) // 3 println("Second element: " + integerList[1]) // 200 // Convert to string array val tagsJson = Json.parse("["audit", "finance", "tax"]") val tags = tagsJson.toStringArray() println("First tag: " + tags[0])

Direct DTO Class Mapping

Autolang supports deserializing JSON payloads directly into class instances or array collections through generics. Properties are mapped automatically from matching JSON keys.

@import("std/json") class CustomerDto { lateinit val id: String lateinit val creditLimit: Int } // 1. Decode single object from JSON string val jsonText = "{\"id\": \"CUST-881\", \"creditLimit\": 50000}" val customer: CustomerDto = Json.decodeFromString<CustomerDto>(jsonText) println("Customer ID: " + customer.id + ", limit: " + customer.creditLimit) // Decode via string extension val directCust = "{\"id\": \"CUST-882\", \"creditLimit\": 75000}".decodeJson<CustomerDto>() println("Direct decoded customer ID: " + directCust.id) // 2. Decode array of objects val batchJson = "[{\"id\": \"CUST-01\", \"creditLimit\": 1000}, {\"id\": \"CUST-02\", \"creditLimit\": 2000}]" val customerList = Json.decodeArrayFromString<CustomerDto>(batchJson) println("Customer list count: " + customerList.size + ", second ID: " + customerList[1].id) // 3. Serialize back to JSON string val serialized = Json.encodeToString(customer) println("Serialized JSON: " + serialized)

Serialization & Indentation

The stringify() method supports producing minified JSON payloads or human-readable indented strings for logging and network wire transfer.

@import("std/json") val payload = Json.emptyObject() payload["action"] = Json.fromString("SYNC_ACCOUNTS") payload["timestamp"] = Json.fromInt(1717171717) // 1. Minified string for wire efficiency (-1) val minified = payload.stringify(-1) println("Minified: " + minified) // 2. Formatted indented string for readability (4 spaces) val formatted = payload.stringify(4) println("Formatted JSON:\n" + formatted)

Method Reference

Constructors & Static Parsers

  • Json.parse(text: String): Json: Parses a JSON string into a tree node.
  • Json.emptyObject(): Json: Creates an empty JSON object node.
  • Json.emptyArray(): Json: Creates an empty JSON array node.
  • Json.fromString(value: String): Json / Json.fromInt(value: Int): Json: Wraps primitive values into JSON nodes.
  • Json.fromFloat(value: Float): Json / Json.fromBool(value: Bool): Json / Json.nullValue(): Json: Wraps float, boolean, and null values.
  • Json.decodeFromString<T>(jsonStr: String): T: Maps a JSON string into an instance of class T.
  • Json.decodeArrayFromString<T>(jsonStr: String): Array<T>: Maps a JSON string into an array of class T instances.
  • Json.encodeToString(node: Json): String: Serializes a JSON node into a string.

Type Inspection

  • has(key: String): Bool: Checks whether a key exists in the object.
  • isObject(): Bool / isArray(): Bool: Tests whether the node is an object or array.
  • isString(): Bool / isNumber(): Bool / isBool(): Bool / isNull(): Bool: Checks the primitive type of the node.
  • getSize(): Int: Returns array length or number of object fields.

Field Access & Manipulation

  • get(key: String): Json / operator [](key: String): Json: Retrieves child node by key.
  • set(key: String, value: Json) / operator []=(key: String, value: Json): Assigns value to key.
  • getString(key: String): String / getInt(key: String): Int: Extracts string or integer value directly.
  • optString(key: String, defaultVal: String): String / optInt(key: String, defaultVal: Int): Int: Extracts value with default fallback.
  • getAt(index: Int): Json / add(value: Json): Array element access and insertion.
  • asString(): String / asInt(): Int / asFloat(): Float / asBool(): Bool: Unboxes node to primitive values.
  • toIntArray(): Array<Int> / toFloatArray(): Array<Float> / toStringArray(): Array<String>: Converts JSON array to primitive array.
  • toClass<T>(): T / decodeTo<T>(): T / toArrayClass<T>(): Array<T>: Deserializes node to class instance.
  • stringify(indent: Int = -1): String: Serializes JSON tree with optional indentation.

String Extension Methods

  • String.parseJson(): Json: Parses string into a JSON node.
  • String.decodeJson<T>(): T: Deserializes string directly into class T.
  • String.decodeJsonArray<T>(): Array<T>: Deserializes string into an array of class T instances.