Commits

Ivan Inozemtsev committed c954745

Pretty printing for json

  • Participants
  • Parent commits b9dbddf

Comments (0)

Files changed (1)

File fan/JsonPrinter.fan

       writeJsonObj(out, obj)
   }
 
+  Str? indent := "  "
+  Str separator := ": "
+  
+  private Int level := 0
+
+  private Void newline(OutStream out)
+  {
+    if(indent == null) return
+    out.writeChar('\n')
+    level.times { out.writeChars(indent) }
+  }
   protected virtual Void writeJsonStr(OutStream out, Str str)
   {
     out.writeChar(JsonToken.quote)
   protected virtual Void writeJsonMap(OutStream out, ConstMap map)
   {
     out.writeChar(JsonToken.objectStart)
-    notFirst := false
-    map.each |entry|
+    if(map.isEmpty)
     {
-      if (notFirst) out.writeChar(JsonToken.comma).writeChar('\n')
+      out.writeChar(JsonToken.objectEnd)
+      return
+    }
+    level++
+    
+    map.each |entry, i|
+    {
+      if (i != 0) out.writeChar(JsonToken.comma)
+      newline(out)
       writeJsonPair(out, entry->key, entry->val)
-      notFirst = true
     }
+    
+    level--
+    newline(out)
     out.writeChar(JsonToken.objectEnd)
   }
 
   protected virtual Void writeJsonList(OutStream out, ConstList array)
   {
     out.writeChar(JsonToken.arrayStart)
-    notFirst := false
-    array.each |item|
+    if(array.isEmpty) 
     {
-      if (notFirst) out.writeChar(JsonToken.comma)
+      out.writeChar(JsonToken.arrayEnd)
+      return
+    }
+    level++
+    notPrimitives := false
+    array.each |item,i|
+    {
+      if (i != 0) out.writeChar(JsonToken.comma)
+      if((item isnot Str) && (item isnot Num) && (item isnot Bool))
+      {
+        newline(out)
+        notPrimitives = true
+      }
       writeJson(out, item)
-      notFirst = true
     }
+    level--
+    if(notPrimitives)
+      newline(out)
     out.writeChar(JsonToken.arrayEnd)
   }
 
   protected virtual Void writeJsonPair(OutStream out, Str key, Obj? val)
   {
     writeJsonStr(out, key)
-    out.writeChar(JsonToken.colon)
+    out.writeChars(separator)
     writeJson(out, val)
   }