changeset 1:4d103b4450ee

Converted a record to JSON
author Adam Chlipala <adam@chlipala.net>
date Thu, 02 Dec 2010 11:35:01 -0500
parents 63697ef80a2c
children 478524b9d23a
files json.ur json.urs tests/testJson.ur
diffstat 3 files changed, 26 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- 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 <xml>Uhoh!</xml>}
--- 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
--- 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 <xml><body>
-  {[Json.toJson (1 :: 2 :: 8 :: [])]}<br/>
-  {[Json.fromJson "[1,2, 8]" : list int]}
+  {[toJson (1 :: 2 :: 8 :: [])]}<br/>
+  {[fromJson "[1,2, 8]" : list int]}
   <hr/>
-  {[Json.toJson (1.2 :: 2.4 :: (-8.8) :: [])]}<br/>
-  {[Json.fromJson "[1.4,-2.7, 8.215506]" : list float]}
+  {[toJson (1.2 :: 2.4 :: (-8.8) :: [])]}<br/>
+  {[fromJson "[1.4,-2.7, 8.215506]" : list float]}
   <hr/>
-  {[Json.toJson ("hi" :: "bye" :: "tricky\\\" one!" :: [])]}<br/>
-  {[Json.fromJson "[\"abc\", \"\\\\whoa\"]" : list string]}
+  {[toJson ("hi" :: "bye" :: "tricky\\\" one!" :: [])]}<br/>
+  {[fromJson "[\"abc\", \"\\\\whoa\"]" : list string]}
   <hr/>
-  {[Json.toJson (True :: False :: True :: [])]}<br/>
-  {[Json.fromJson "[true,false, true]" : list bool]}
+  {[toJson (True :: False :: True :: [])]}<br/>
+  {[fromJson "[true,false, true]" : list bool]}
+  <hr/>
+  {[toJson {A = 1, B = 2.3, C = "Hi", D = True}]}
 </body></xml>