mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 16:54:25 +00:00
import json import path import time import proc -- found in std/ after the program's own files, so a program's own json.fch always wins. path: join, base, dir, ext, stem, parts, clean, is_abs. time: now, millis, sleep, date, local, format, days_in_month (clock_gettime, strftime through C import). proc: run, output (an error with the command's output when it fails), env, pid, cwd. json: parse (errors with line and column), stringify, pretty, new_*, get/at/set/push/has/names and str_or/int_or/float_or/bool_or; \u escapes with surrogate pairs. The C importer now leaves a plain (non-const) char * parameter a ptr[char], a buffer C writes into; only const char * is text going in. str(ptr) and str([]u8) are in the self-hosted compiler. boot.sh: 40 passed, 0 failed.
35 lines
1.5 KiB
Text
35 lines
1.5 KiB
Text
import json
|
|
|
|
fn main() -> ! {
|
|
doc := try json.parse("{\"name\": \"Finch\", \"tags\": [\"fast\", \"small\"], \"stars\": 5, \"pi\": 3.25, \"ok\": true, \"none\": null, \"nested\": {\"deep\": [1, [2, 3]]}}")
|
|
print(doc.get("name").str_or(""), doc.get("tags").at(1).str_or(""), doc.get("stars").int_or(0), doc.get("pi").float_or(0.0))
|
|
print(doc.get("ok").bool_or(false), doc.get("none").is_null(), doc.get("missing").is_null(), doc.has("name"), doc.has("nope"))
|
|
print(doc.get("nested").get("deep").at(1).at(0).int_or(-1), doc.get("tags").len(), doc.names())
|
|
print(json.stringify(doc))
|
|
|
|
out := json.new_object()
|
|
out.set("greeting", json.new_text("hi \"there\"\n"))
|
|
list := json.new_list()
|
|
list.push(json.new_number(1))
|
|
list.push(json.new_number(2.5))
|
|
list.push(json.new_bool(false))
|
|
list.push(json.new_null())
|
|
out.set("values", list)
|
|
out.set("greeting", json.new_text("replaced"))
|
|
out.set("empty", json.new_object())
|
|
print(json.stringify(out))
|
|
print(json.pretty(out))
|
|
|
|
again := try json.parse(json.pretty(out))
|
|
print(json.stringify(again) == json.stringify(out))
|
|
print((try json.parse("\"caf\\u00e9 \\ud83d\\ude00 \\/\"")).str_or(""))
|
|
print((try json.parse(" [ ] ")).len(), (try json.parse("-12.5e1")).float_or(0.0))
|
|
|
|
for bad in ["{\"a\": }", "[1, 2", "{\"a\" 1}", "tru", "[1] x", "\"open", "", "[1,\n oops]"] {
|
|
json.parse(bad) or {
|
|
print(err)
|
|
continue
|
|
}
|
|
print("parsed?!", bad)
|
|
}
|
|
}
|