Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 72 lines (54 sloc) 2.228 kb
7542586 @lpsmith Add Json type, which when used abstractly guarantees valid Json syntax
authored
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module : Data.Json.Builder.Internal
4 -- Copyright : (c) 2011 Leon P Smith
5 -- License : BSD3
6 --
7 -- Maintainer : Leon P Smith <leon@melding-monads.com>
8 --
9 -- Internal bits. You can break this library's abstraction and emit
10 -- invalid Json syntax the constructors provided in this module.
11 -----------------------------------------------------------------------------
12
13 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
14
15 module Data.Json.Builder.Internal
16 ( Value (..)
17 , Json (..)
18 , JsString(..)
19 , Escaped (..)
20 ) where
21
22 import Prelude hiding ((++))
23
24 import Blaze.ByteString.Builder
25 import Blaze.ByteString.Builder.Char.Utf8 ( fromChar )
26 import Data.ByteString(ByteString)
27 import Data.Monoid
28
29 (++) :: Monoid a => a -> a -> a
30 (++) = mappend
31 infixr 5 ++
32
33 -- | The 'Value' typeclass represents types that can be rendered
34 -- into valid json syntax.
35
36 class Value a where
37 toJson :: a -> Json
38
39 -- | The 'Json' type represents valid json syntax. It cannot be directly
40 -- analyzed, however it can be rendered into a 'ByteString' and used to
41 -- as a component of an array or an object to build a bigger json value.
42
43 newtype Json = Json Builder
44
45 instance Value Json where
46 toJson = id
47
48 -- | The 'String' typeclass represents types that render into json string
49 -- syntax. They are special because only strings can appear as field names
50 -- of json objects.
51
52 class Value a => JsString a where
53 escape :: a -> Escaped
54
55 -- | The 'Escaped' type represents json string syntax. The purpose of this
56 -- type is so that json strings can be efficiently constructed from multiple
57 -- Haskell strings without superfluous conversions or concatinations.
58 --
59 -- Internally, it is just a 'Builder' value which must produce a UTF-8 encoded
60 -- bytestring with backslashes, quotes, and control characters appropriately
61 -- escaped. It also must not render the opening or closing quote, which
62 -- are instead rendered by 'toJson'.
63
64 newtype Escaped = Escaped Builder deriving (Monoid)
65
66 instance Value Escaped where
67 toJson (Escaped str) = Json (fromChar '"' ++ str ++ fromChar '"')
68
69 instance JsString Escaped where
70 escape = id
71
Something went wrong with that request. Please try again.