Ivan Inozemtsev avatar Ivan Inozemtsev committed c954745

Pretty printing for json

Comments (0)

Files changed (1)

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)
   }
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.