on master help sign in
Introduce "ugly" encoding

Allow more compact representation

commit4cc8b091eea8cbf734f4632db4ec464d93bc1032 authorEvan Czaplicki <evancz@users.noreply.github.com> dateMon 19 Jun 2017, 15:04 (9 years ago) parent572f3c2
1 file changed+48
src/Json/Encode.hs+48
src/Json/Encode.hs+48
@@ -3,6 +3,8 @@
33module Json.Encode
44 ( write
55 , encode
6+ , writeUgly
7+ , encodeUgly
68 , Value
79 , array
810 , object
@@ -106,6 +108,52 @@ write path value =
106108 B.hPutBuilder handle (encode value)
107109
108110
111+writeUgly :: FilePath -> Value -> IO ()
112+writeUgly path value =
113+ withBinaryFile path WriteMode $ \handle ->
114+ B.hPutBuilder handle (encodeUgly value)
115+
116+
117+
118+-- ENCODE UGLY
119+
120+
121+encodeUgly :: Value -> B.Builder
122+encodeUgly value =
123+ case value of
124+ Array [] ->
125+ B.string7 "[]"
126+
127+ Array (first : rest) ->
128+ let
129+ encodeEntry entry =
130+ B.char7 ',' <> encodeUgly entry
131+ in
132+ B.char7 '[' <> encodeUgly first <> mconcat (map encodeEntry rest) <> B.char7 ']'
133+
134+ Object [] ->
135+ B.string7 "{}"
136+
137+ Object (first : rest) ->
138+ let
139+ encodeEntry char (key, entry) =
140+ B.char7 char <> encodeString key <> B.char7 ':' <> encodeUgly entry
141+ in
142+ encodeEntry '[' first <> mconcat (map (encodeEntry ',') rest) <> B.char7 ']'
143+
144+ String builder ->
145+ builder
146+
147+ Boolean boolean ->
148+ B.string7 (if boolean then "true" else "false")
149+
150+ Integer n ->
151+ B.intDec n
152+
153+ Null ->
154+ "null"
155+
156+
109157
110158-- ENCODE
111159