on master help sign in
indented JSON formatting
commit5194c073fde26eaa4560cd5e55a70259fec8f253 authorMichael Morgan <morgan.michael@me.com> dateMon 4 Dec 2017, 11:45 (9 years ago) parent075504a
1 file changed+35
libs/contrib/Language/JSON/Data.idr+35
libs/contrib/Language/JSON/Data.idr+35
@@ -1,5 +1,7 @@
11module Language.JSON.Data
22
3+import Data.String.Extra
4+
35%access private
46%default total
57
@@ -61,3 +63,36 @@ stringify (JObject xs) = "{" ++ stringifyProps xs ++ "}"
6163export
6264Show JSON where
6365 show = stringify
66+
67+||| Format a JSON value, indenting by `n` spaces per nesting level.
68+|||
69+||| @curr The current indentation amount, measured in spaces.
70+||| @n The amount of spaces to indent per nesting level.
71+export
72+format : {default 0 curr : Nat} -> (n : Nat) -> JSON -> String
73+format {curr} n json = indent curr $ formatValue curr n json
74+ where
75+ formatValue : (curr, n : Nat) -> JSON -> String
76+ formatValue _ _ (JArray []) = "[]"
77+ formatValue curr n (JArray xs@(_ :: _)) = "[\n" ++ formatValues xs
78+ ++ indent curr "]"
79+ where
80+ formatValues : (xs : List JSON) -> {auto ok : NonEmpty xs} -> String
81+ formatValues (x :: xs) = format {curr=(curr + n)} n x
82+ ++ case nonEmpty xs of
83+ Yes ok => ",\n" ++ formatValues xs
84+ No _ => "\n"
85+ formatValue _ _ (JObject []) = "{}"
86+ formatValue curr n (JObject xs@(_ :: _)) = "{\n" ++ formatProps xs
87+ ++ indent curr "}"
88+ where
89+ formatProp : (String, JSON) -> String
90+ formatProp (key, value) = indent (curr + n) (showString key ++ ": ")
91+ ++ formatValue (curr + n) n value
92+
93+ formatProps : (xs : List (String, JSON)) -> {auto ok : NonEmpty xs} -> String
94+ formatProps (x :: xs) = formatProp x
95+ ++ case nonEmpty xs of
96+ Yes ok => ",\n" ++ formatProps xs
97+ No _ => "\n"
98+ formatValue _ _ x = stringify x