From e976947f26185219352783103dd79ff55242d1da Mon Sep 17 00:00:00 2001 From: Robert Soeldner Date: Mon, 14 Oct 2024 16:51:37 +0200 Subject: [PATCH] add basic json accessors --- examples/json/Json.sig | 7 ++++++ examples/json/Json.sml | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/examples/json/Json.sig b/examples/json/Json.sig index 4b94ef51b7..3c22504cb3 100644 --- a/examples/json/Json.sig +++ b/examples/json/Json.sig @@ -20,6 +20,13 @@ sig val fromString : string -> json list * substring val fromFile : string -> json list * substring + val getObject : json -> string -> json option + val getBool : json -> bool option + val getString : json -> string option + val getInt : json -> int option + val getFloat : json -> real option + + val pp_json : json PP.pprinter end diff --git a/examples/json/Json.sml b/examples/json/Json.sml index c0775c4ee0..1f154287ab 100644 --- a/examples/json/Json.sml +++ b/examples/json/Json.sml @@ -277,4 +277,53 @@ val pp_json = val _ = PolyML.addPrettyPrinter (fn d => fn _ => fn json => pp_json json); + +(* accessors *) + +fun getObject json k = + case json of + AList al => Option.map #2 (List.find (fn (key, _) => key = k) al) + | _ => NONE + +fun getBool json = + case json of + Boolean b => SOME b + | _ => NONE + +fun getString json = + case json of + String str => SOME str + | _ => NONE + +fun getInt json = + case json of + Number (Int i) => SOME i + | _ => NONE + +fun getFloat json = + case json of + Number (Float f) => SOME f + | _ => NONE + +fun foldlArray json (f: json -> 'a option) = + let + fun seq [] = SOME [] + | seq (NONE :: _) = NONE + | seq (SOME x :: xs) = + case seq xs of + NONE => NONE + | SOME ys => SOME (x :: ys) + in + case json of + List l => seq (List.map f l) + | _ => NONE + end + +(* val json = hd (#1 (parse ([],Substring.full "{\"foo\" : [1, 23, 4], \"bar\" : 2}"))) *) +(* val foo = getObject json "foo" *) +(* val foo_ints = foldlArray (valOf foo) getInt *) +(* val json_str = getString json *) +(* val bar = getObject json "bar" *) + + end (* Json *)