aboutsummaryrefslogtreecommitdiff
path: root/Utility/JSONStream.hs
blob: 2746678ccff22460e12e3b2a47f0165517cb2308 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{- Streaming JSON output.
 -
 - Copyright 2011 Joey Hess <id@joeyh.name>
 -
 - License: BSD-2-clause
 -}

module Utility.JSONStream (
	start,
	add,
	end
) where

import Text.JSON

{- Text.JSON does not support building up a larger JSON document piece by
 - piece as a stream. To support streaming, a hack. The JSObject is converted
 - to a string with its final "}" is left off, allowing it to be added to
 - later. -}
start :: JSON a => [(String, a)] -> String
start l
	| last s == endchar = init s
	| otherwise = bad s
  where
	s = encodeStrict $ toJSObject l

add :: JSON a => [(String, a)] -> String
add l
	| head s == startchar = ',' : drop 1 s
	| otherwise = bad s
  where
	s = start l

end :: String
end = [endchar, '\n']

startchar :: Char
startchar = '{'

endchar :: Char
endchar = '}'

bad :: String -> a
bad s = error $ "Text.JSON returned unexpected string: " ++ s