json

The json module parses JSON into navigable values, queries and edits JSON strings by key, merges and reshapes objects and arrays, pretty-prints or minifies, and streams large arrays or NDJSON one value at a time. Import it with import json.

Parsing and serialization

FunctionSignatureDescription
validjson.valid(s: string) → boolWhether s is valid JSON
parsejson.parse(s: string) → anyParse into a navigable object/array/scalar tree
stringifyjson.stringify(v: any, indent?: string) → stringSerialize a value; pass an indent for pretty output. Keys are sorted
prettyjson.pretty(s: string) → stringRe-indent existing JSON text with 2 spaces
minifyjson.minify(s: string) → stringStrip whitespace from JSON text

Querying

These operate on a JSON string and read top-level keys.

FunctionSignatureDescription
getjson.get(j: string, key: string) → stringValue at key as a string; empty if missing/null
getIntjson.getInt(j: string, key: string) → intValue at key as int; 0 if missing/non-numeric
getBooljson.getBool(j: string, key: string) → boolValue at key as bool; false if missing
hasjson.has(j: string, key: string) → boolWhether key exists
keysjson.keys(obj: any) → string[]Sorted field names of a parsed object or JSON string
lengthjson.length(j: string) → intObject key count or array length
arrayGetjson.arrayGet(j: string, idx: int) → stringElement at idx of a JSON array

Editing

These return a new JSON string with the change applied.

FunctionSignatureDescription
setStringjson.setString(j: string, key: string, val: string) → stringSet key to a string value
setIntjson.setInt(j: string, key: string, val: int) → stringSet key to an int value
setBooljson.setBool(j: string, key: string, val: bool) → stringSet key to a bool value
deletejson.delete(j: string, key: string) → stringRemove key
mergejson.merge(j1: string, j2: string) → stringMerge two objects; j2 keys overwrite j1
fromArrayjson.fromArray(arr: string[]) → stringConvert an array into a JSON array string

json.stream

Streams a JSON source one top-level value at a time, calling fn(value) for each. Handles both a JSON array (each element delivered separately) and concatenated values or NDJSON. The callback may return false to stop early. Returns the count of values delivered.

FunctionSignatureDescription
parseStringjson.stream.parseString(s: string, fn) → intStream values from a JSON string
parseFilejson.stream.parseFile(path: string, fn) → intStream values from a JSON file

Example

import json

let doc = json.parse("{\"name\": \"alice\", \"age\": 30}")
print(doc.name)                         // alice

let updated = json.setInt("{\"age\": 30}", "age", 31)
print(updated)

json.stream.parseString("[1, 2, 3]", fn(v) {
    print(v)
    return true
})
Standard library · View as Markdown · llms-full.txt