system.json

JSON parsing and serialization.

import system.json as json

Parsing JSON

parse(string)

Parse JSON string into Quartz value.

// Parse object
let data = json.parse('{"name": "Alice", "age": 30}')
io.println(data["name"])  // "Alice"
io.println(data["age"])   // 30

// Parse array
let arr = json.parse('[1, 2, 3, 4, 5]')
io.println(arr[0])        // 1

// Parse primitives
let num = json.parse("42")
let str = json.parse('"hello"')
let bool = json.parse("true")

Type Mapping

JSON Type Quartz Type Example
objectdict`{"a": 1}` → `{"a": 1}`
arrayarray`[1, 2]` → `[1, 2]`
stringstring`"hi"` → `"hi"`
number (int)int`42` → `42`
number (float)double`3.14` → `3.14`
booleanbool`true` → `true`
nullnull`null` → `null`

Serializing to JSON

stringify(value)

Convert Quartz value to JSON string.

let data = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"]
}

let jsonStr = json.stringify(data)
io.println(jsonStr)
// {"name":"Alice","age":30,"hobbies":["reading","coding"]}

stringify(value, indent)

Pretty-print with indentation.

let data = {
"name": "Alice",
"scores": [95, 87, 92]
}

let pretty = json.stringify(data, 2)
io.println(pretty)

Output:

{
"name": "Alice",
"scores": [
95,
87,
92
]
}

Validation

isValid(string)

Check if string is valid JSON.

json.isValid('{"valid": true}')   // true
json.isValid('{invalid}')          // false
json.isValid('[1, 2, 3]')          // true
json.isValid('not json')           // false

Safe Parsing

fn safeParse(str) {
try {
return json.parse(str)
} catch (e) {
io.eprintln("JSON parse error: " + e.message)
return null
}
}

let data = safeParse('{"key": "value"}')
if (data != null) {
io.println(data["key"])
}

File Operations

Reading JSON Files

import system.json as json
import system.fs as fs

fn readJsonFile(path) {
let content = fs.readFile(path)
return json.parse(content)
}

let config = readJsonFile("config.json")
io.println("Server: " + config["server"])
io.println("Port: " + config["port"])

Writing JSON Files

import system.json as json
import system.fs as fs

fn writeJsonFile(path, data) {
let content = json.stringify(data, 2)
fs.writeFile(path, content)
}

let settings = {
"theme": "dark",
"fontSize": 14,
"autoSave": true
}

writeJsonFile("settings.json", settings)

Examples

Configuration File

import system.json as json
import system.fs as fs
import system.io as io

class Config {
constructor(path) {
self.path = path
self.data = {}
self.load()
}

fn load() {
if (fs.exists(self.path)) {
let content = fs.readFile(self.path)
self.data = json.parse(content)
}
}

fn save() {
let content = json.stringify(self.data, 2)
fs.writeFile(self.path, content)
}

fn get(key, default = null) {
if (self.data[key] != null) {
return self.data[key]
}
return default
}

fn set(key, value) {
self.data[key] = value
self.save()
}
}

let config = Config("app.json")
io.println("Theme: " + config.get("theme", "light"))
config.set("theme", "dark")

API Response Handler

import system.json as json

fn handleApiResponse(response) {
let data = json.parse(response)

if (data["error"] != null) {
io.eprintln("API Error: " + data["error"]["message"])
return null
}

return data["result"]
}

// Example response
let response = '{"result": {"id": 1, "name": "Test"}, "error": null}'
let result = handleApiResponse(response)

if (result != null) {
io.println("ID: " + result["id"])
io.println("Name: " + result["name"])
}

Data Transform

import system.json as json

// Transform array of objects
fn transformUsers(jsonStr) {
let users = json.parse(jsonStr)
let result = []

for (let i = 0; i < len(users); i = i + 1) {
let user = users[i]
result[i] = {
"fullName": user["firstName"] + " " + user["lastName"],
"email": user["email"]
}
}

return json.stringify(result, 2)
}

let input = '[{"firstName":"John","lastName":"Doe","email":"john@test.com"}]'
io.println(transformUsers(input))

Nested Data Access

import system.json as json

let jsonStr = '{"user":{"profile":{"name":"Alice","settings":{"theme":"dark"}}}}'
let data = json.parse(jsonStr)

// Deep access
let name = data["user"]["profile"]["name"]
let theme = data["user"]["profile"]["settings"]["theme"]

io.println("Name: " + name)   // Alice
io.println("Theme: " + theme) // dark

// Safe nested access function
fn getPath(obj, path) {
let parts = str.split(path, ".")
let current = obj

for (let i = 0; i < len(parts); i = i + 1) {
if (current == null) {
return null
}
current = current[parts[i]]
}

return current
}

let themeSafe = getPath(data, "user.profile.settings.theme")
io.println("Theme: " + themeSafe)

💡 Tip Always validate JSON input, especially from external sources. Use isValid() or try-catch to handle malformed JSON gracefully.

Next: system.time →