Skip to content

Commit

Permalink
add basic json accessors
Browse files Browse the repository at this point in the history
  • Loading branch information
rsoeldner committed Oct 14, 2024
1 parent 9ee2f86 commit e976947
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions examples/json/Json.sig
Original file line number Diff line number Diff line change
Expand Up @@ -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
49 changes: 49 additions & 0 deletions examples/json/Json.sml
Original file line number Diff line number Diff line change
Expand Up @@ -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 *)

0 comments on commit e976947

Please sign in to comment.