summaryrefslogtreecommitdiff
path: root/Utility/JSONStream.hs
blob: 45978ef06f6c7f363025bf92a473629a7dc5da7d (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
{- Streaming JSON output.
 -
 - Copyright 2011, 2016 Joey Hess <id@joeyh.name>
 -
 - License: BSD-2-clause
 -}

{-# LANGUAGE GADTs, OverloadedStrings #-}

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

import Data.Aeson
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.UTF8 as BU8
import Data.Char
import Data.Word

data JSONChunk v where
	AesonObject :: Object -> JSONChunk Object
	JSONChunk :: ToJSON v => [(String, v)] -> JSONChunk [(String, v)]

encodeJSONChunk :: JSONChunk v -> B.ByteString
encodeJSONChunk (AesonObject o) = encode o
encodeJSONChunk (JSONChunk l) = encode $ object $ map mkPair l
  where
	mkPair (s, v) = (T.pack s, toJSON v)

{- Aeson does not support building up a larger JSON object piece by piece
 - with streaming output. To support streaming, a hack:
 - The final "}" is left off the JSON, allowing more chunks to be added
 - to later. -}
start :: JSONChunk a -> B.ByteString
start a
	| not (B.null b) && B.last b == endchar = B.init b
	| otherwise = bad b
  where
	b = encodeJSONChunk a

add :: JSONChunk a -> B.ByteString
add a
	| not (B.null b) && B.head b == startchar = 
		B.cons addchar (B.drop 1 b)
	| otherwise = bad b
  where
	b = start a

addNestedObject :: String -> B.ByteString -> B.ByteString
addNestedObject s b = B.concat
	[ ",\""
	, BU8.fromString s
	, "\":"
	, b
	, "}"
	]

end :: B.ByteString
end = endchar `B.cons` sepchar `B.cons` B.empty

startchar :: Word8
startchar = fromIntegral (ord '{')

endchar :: Word8
endchar = fromIntegral (ord '}')

addchar :: Word8
addchar = fromIntegral (ord ',')

sepchar :: Word8
sepchar = fromIntegral (ord '\n')

bad :: B.ByteString -> a
bad b = error $ "JSON encoder generated unexpected value: " ++ show b