@@ -21,7 +21,8 @@ import Text.Parsec.Text (Parser)
2121data Expr = IntLiteral ! Integer
2222 | DoubleLiteral ! Scientific
2323 | StringLiteral ! Text
24- | JsonLiteral ! Value
24+ | ObjectLiteral ! Value
25+ | ArrayLiteral ! Value
2526 | FunctionCall ! Function
2627 deriving (Show , Eq )
2728
@@ -44,25 +45,26 @@ expr = literal <|> functionCall
4445
4546
4647literal :: Parser Expr
47- literal = number <|> stringLiteral <|> jsonLiteral
48+ literal = number <|> stringLiteral <|> objectLiteral <|> arrayLiteral
4849
4950
5051showExpr :: Expr -> Text
5152showExpr (StringLiteral s) = " \" " <> s <> " \" "
5253showExpr (IntLiteral n) = T. pack . show $ n
5354showExpr (DoubleLiteral n) = T. pack . show $ n
54- showExpr (JsonLiteral s) = TL. toStrict . TL. decodeUtf8 $ encode s
55+ showExpr (ObjectLiteral s) = TL. toStrict . TL. decodeUtf8 $ encode s
56+ showExpr (ArrayLiteral a) = TL. toStrict . TL. decodeUtf8 $ encode a
5557showExpr (FunctionCall _) = error " Can only convert literals to text representation"
5658
5759
58- jsonLiteral :: Parser Expr
59- jsonLiteral = do
60+ objectLiteral :: Parser Expr
61+ objectLiteral = do
6062 assignments <- between (char ' {' ) (char ' }' ) (assignment `sepBy` comma)
6163 let
6264 objStr = " {" <> T. intercalate " , " assignments <> " }"
6365 case decode' (TL. encodeUtf8 . TL. fromStrict $ objStr) of
6466 Nothing -> error $ " Invalid JSON string: " <> T. unpack objStr
65- Just v -> pure $ JsonLiteral v
67+ Just v -> pure $ ObjectLiteral v
6668 where
6769 assignment = do
6870 key <- stringLiteral
@@ -73,6 +75,19 @@ jsonLiteral = do
7375 comma = char ' ,' >> spaces
7476
7577
78+ arrayLiteral :: Parser Expr
79+ arrayLiteral = do
80+ elements <- between (char ' [' ) (char ' ]' ) (element `sepBy` comma)
81+ let
82+ arrStr = " [" <> T. intercalate " , " elements <> " ]"
83+ case decode' (TL. encodeUtf8 . TL. fromStrict $ arrStr) of
84+ Nothing -> error $ " Invalid JSON string: " <> T. unpack arrStr
85+ Just v -> pure $ ArrayLiteral v
86+ where
87+ element = showExpr <$> literal
88+ comma = char ' ,' >> spaces
89+
90+
7691number :: Parser Expr
7792number = do
7893 integer <- many1 digit
@@ -138,9 +153,12 @@ ident = do
138153-- Right (StringLiteral "")
139154--
140155-- >>> parseExpr "{}"
141- -- Right (JsonLiteral (Object (fromList [])))
156+ -- Right (ObjectLiteral (Object (fromList [])))
142157--
143158-- >>> parseExpr "{\"x\": 10, \"y\": {}}"
144- -- Right (JsonLiteral (Object (fromList [("x",Number 10.0),("y",Object (fromList []))])))
159+ -- Right (ObjectLiteral (Object (fromList [("x",Number 10.0),("y",Object (fromList []))])))
160+ --
161+ -- >>> parseExpr "[10, 20, 30]"
162+ -- Right (ArrayLiteral (Array [Number 10.0,Number 20.0,Number 30.0]))
145163parseExpr :: Text -> Either ParseError Expr
146164parseExpr = parse expr " (unknown)"
0 commit comments