# HG changeset patch # User Adam Chlipala # Date 1291307701 18000 # Node ID 4d103b4450ee9e8725db1076af65c847777214b6 # Parent 63697ef80a2c9cfffbc0399a6ee33aeddd59faf9 Converted a record to JSON diff -r 63697ef80a2c -r 4d103b4450ee json.ur --- a/json.ur Thu Dec 02 11:10:57 2010 -0500 +++ b/json.ur Thu Dec 02 11:35:01 2010 -0500 @@ -190,3 +190,12 @@ {ToJson = toJ, FromJson = fromJ} end + +fun json_record [ts ::: {Type}] (fl : folder ts) (jss : $(map json ts)) (names : $(map (fn _ => string) ts)) : json $ts = + {ToJson = fn r => "{" ^ @foldR3 [json] [fn _ => string] [id] [fn _ => string] + (fn [nm ::_] [t ::_] [r ::_] [[nm] ~ r] (j : json t) name v acc => + escape name ^ ":" ^ j.ToJson v ^ (case acc of + "" => "" + | _ => "," ^ acc)) + "" fl jss names r ^ "}", + FromJson = fn _ => error Uhoh!} diff -r 63697ef80a2c -r 4d103b4450ee json.urs --- a/json.urs Thu Dec 02 11:10:57 2010 -0500 +++ b/json.urs Thu Dec 02 11:35:01 2010 -0500 @@ -11,3 +11,5 @@ val json_float : json float val json_bool : json bool val json_list : a ::: Type -> json a -> json (list a) + +val json_record : ts ::: {Type} -> folder ts -> $(map json ts) -> $(map (fn _ => string) ts) -> json $ts diff -r 63697ef80a2c -r 4d103b4450ee tests/testJson.ur --- a/tests/testJson.ur Thu Dec 02 11:10:57 2010 -0500 +++ b/tests/testJson.ur Thu Dec 02 11:35:01 2010 -0500 @@ -1,13 +1,20 @@ +open Json + +val json_abcd : json {A : int, B : float, C : string, D : bool} = + json_record {A = "a", B = "b", C = "c", D = "d"} + fun main () : transaction page = return - {[Json.toJson (1 :: 2 :: 8 :: [])]}
- {[Json.fromJson "[1,2, 8]" : list int]} + {[toJson (1 :: 2 :: 8 :: [])]}
+ {[fromJson "[1,2, 8]" : list int]}
- {[Json.toJson (1.2 :: 2.4 :: (-8.8) :: [])]}
- {[Json.fromJson "[1.4,-2.7, 8.215506]" : list float]} + {[toJson (1.2 :: 2.4 :: (-8.8) :: [])]}
+ {[fromJson "[1.4,-2.7, 8.215506]" : list float]}
- {[Json.toJson ("hi" :: "bye" :: "tricky\\\" one!" :: [])]}
- {[Json.fromJson "[\"abc\", \"\\\\whoa\"]" : list string]} + {[toJson ("hi" :: "bye" :: "tricky\\\" one!" :: [])]}
+ {[fromJson "[\"abc\", \"\\\\whoa\"]" : list string]}
- {[Json.toJson (True :: False :: True :: [])]}
- {[Json.fromJson "[true,false, true]" : list bool]} + {[toJson (True :: False :: True :: [])]}
+ {[fromJson "[true,false, true]" : list bool]} +
+ {[toJson {A = 1, B = 2.3, C = "Hi", D = True}]}