Newer
Older
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
81
82
83
84
85
86
87
88
89
-- |
-- Module: JSONInput
-- Description: Parser for (simplified) JSON values.
module JSONInput where
import JSON
import Result
import ParserCombinators
-- This is the JSON parser from the Week08 notes, adjusted to work
-- with the slightly different parser combinator API in
-- ParserCombinators.
parseJSONBool :: Parser Bool
parseJSONBool =
do stringLiteral "true"
return True
`orElse`
do stringLiteral "false"
return False
parseNull :: Parser ()
parseNull =
do stringLiteral "null"
return ()
comma :: Parser ()
comma = isChar ','
spacedComma :: Parser ()
spacedComma =
do whitespaces
isChar ','
whitespaces
parseList :: Parser a -> Parser [a]
parseList p =
do isChar '['
whitespaces
xs <- sepBy spacedComma p
whitespaces
isChar ']'
return xs
parseObjectItem :: Parser a -> Parser (String, a)
parseObjectItem p =
do fieldname <- quotedString
whitespaces
isChar ':'
whitespaces
value <- p
return (fieldname, value)
parseObject :: Parser a -> Parser [(String,a)]
parseObject p =
do isChar '{'
whitespaces
xs <- sepBy spacedComma (parseObjectItem p)
whitespaces
isChar '}'
return xs
parseJSON :: Parser JSON
parseJSON =
do num <- number
return (JsonInteger num)
`orElse`
do s <- quotedString
return (JsonString s)
`orElse`
do b <- parseJSONBool
return (JsonBoolean b)
`orElse`
do parseNull
return JsonNull
`orElse`
do items <- parseList parseJSON
return (JsonArray items)
`orElse`
do fields <- parseObject parseJSON
return (JsonObject fields)
`orElse`
do failParse "Expecting a JSON Value"
-- | Parses a JSON value from a string. Trailing whitespace is ignored.
stringToJSON :: String -> Result JSON
stringToJSON = completeParse (do json <- parseJSON
whitespaces
return json)