License | BSD-style |
---|---|
Maintainer | palkovsky.ondrej@gmail.com |
Stability | experimental |
Portability | portable |
Safe Haskell | None |
Language | Haskell2010 |
An incremental applicative-style JSON parser, suitable for high performance memory efficient stream parsing.
The parser is using Data.Aeson types and FromJSON
instance, it can be
easily combined with aeson monadic parsing instances when appropriate.
- data Parser a
- data ParseOutput a
- = ParseYield a (ParseOutput a)
- | ParseNeedData (ByteString -> ParseOutput a)
- | ParseFailed String
- | ParseDone ByteString
- runParser :: Parser a -> ParseOutput a
- runParser' :: Parser a -> ByteString -> ParseOutput a
- parseByteString :: Parser a -> ByteString -> [a]
- parseLazyByteString :: Parser a -> ByteString -> [a]
- value :: FromJSON a => Parser a
- string :: Parser Text
- bytestring :: Parser ByteString
- safeString :: Int -> Parser Text
- number :: Parser Scientific
- integer :: (Integral i, Bounded i) => Parser i
- real :: RealFloat a => Parser a
- bool :: Parser Bool
- jNull :: Parser ()
- (.:) :: Text -> Parser a -> Parser a
- (.:?) :: Text -> Parser a -> Parser (Maybe a)
- (.!=) :: Parser (Maybe a) -> a -> Parser a
- (.!) :: Int -> Parser a -> Parser a
- objectWithKey :: Text -> Parser a -> Parser a
- objectItems :: Parser a -> Parser (Text, a)
- objectValues :: Parser a -> Parser a
- arrayOf :: Parser a -> Parser a
- arrayWithIndexOf :: Int -> Parser a -> Parser a
- indexedArrayOf :: Parser a -> Parser (Int, a)
- nullable :: Parser a -> Parser (Maybe a)
- defaultValue :: a -> Parser a -> Parser a
- filterI :: (a -> Bool) -> Parser a -> Parser a
- takeI :: Int -> Parser a -> Parser a
- toList :: Parser a -> Parser [a]
How to use this library
>>> parseByteString value "[1,2,3]" :: [[Int]] [[1,2,3]]
The value
parser matches any FromJSON
value. The above command is essentially
identical to the aeson decode function; the parsing process can generate more
objects, therefore the results is [a].
Example of json-stream style parsing:
>>> parseByteString (arrayOf integer) "[1,2,3]" :: [Int] [1,2,3]
Parsers can be combinated using <*>
and <|>
operators. The parsers are
run in parallel and return combinations of the parsed values.
JSON: text = [{"name": "John", "age": 20}, {"age": 30, "name": "Frank"} ] >>> let parser = arrayOf $ (,) <$> "name" .: string <*> "age" .: integer >>> parseByteString parser text :: [(Text,Int)] [("John",20),("Frank",30)]
When parsing larger values, it is advisable to use lazy ByteStrings. The parsing is then more memory efficient as less lexical state is needed to be held in memory for parallel parsers.
More examples are available on https://github.com/ondrap/json-stream.
Performance
The parser tries to do the least amount of work to get the job done. The speed is limited mostly by the lexer (which is not very good). The parser itself is quite efficient in eliminating the work that does not need to be done.
This can become quite significant if the resulting structure contains only a subset of the data.
The parser skips pieces that are not relevant. Using parsers string
, integer
etc. is preferable
to the FromJSON value
.
It is possible to use the *>
operator to filter objects based on a condition, e.g.:
arrayOf $ id <$> "error" .: number *> "name" .: string
This will return all objects that contain attribute error with number content. The parser will skip trying to decode the name attribute if error is not found.
Constant space decoding
Constant space decoding is possible if the grammar does not specify non-constant
operations. The non-constant operations are value
, string
, toList
and in some instances
<*>
.
The value
parser works by creating an aeson AST and passing it to the
parseJSON
method. The AST can consume a lot of memory before it is rejected
in parseJSON
. To achieve constant space the parsers safeString
, number
, integer
,
real
and bool
must be used; these parsers reject and do not parse data if it does not match the
type.
The object key length is limited to ~64K. Object records with longer key are ignored and unparsed.
The toList
parser works by accumulating all matched values. Obviously, number
of such values influences the amount of used memory.
The <*>
operator runs both parsers in parallel and when they are both done, it
produces combinations of the received values. It is constant-space as long as the
number of element produced by child parsers is limited by a constant. This can be achieved by using
.!
and .:
functions combined with constant space
parsers or limiting the number of returned elements with takeI
.
If the source object contains an object with multiple keys with a same name,
json-stream matches the key multiple times. The only exception
is objectWithKey
(.:
and .:?
) that return at most one value for a given key.
Aeson compatibility
The parser uses internally Data.Aeson types, so that the FromJSON instances are
directly usable with the value
parser. It may be more convenient to parse the
outer structure with json-stream and the inner objects with aeson as long as constant-space
decoding is not required.
Json-stream defines the object-access operators .:
, .:?
and .!=
,
but in a slightly different albeit more natural way.
-- JSON: [{"name": "test1", "value": 1}, {"name": "test2", "value": null}, {"name": "test3"}] >>> let person = (,) <$> "name" .: string >>> <*> "value" .:? integer .!= (-1) >>> let people = arrayOf person >>> parseByteString people (..JSON..) [("test1",1),("test2",-1),("test3",-1)]
The Parser
type
A representation of the parser.
data ParseOutput a Source
Result of parsing. Contains continuations to continue parsing.
ParseYield a (ParseOutput a) | Returns a value from a parser. |
ParseNeedData (ByteString -> ParseOutput a) | Parser needs more data to continue parsing. |
ParseFailed String | Parsing failed, error is reported. |
ParseDone ByteString | Parsing finished, unparsed data is returned. |
Parsing functions
runParser :: Parser a -> ParseOutput a Source
Run streaming parser, immediately returns ParseNeedData
.
runParser' :: Parser a -> ByteString -> ParseOutput a Source
Run streaming parser with initial input.
parseByteString :: Parser a -> ByteString -> [a] Source
Parse a bytestring, generate lazy list of parsed values. If an error occurs, throws an exception.
parseLazyByteString :: Parser a -> ByteString -> [a] Source
Parse a lazy bytestring, generate lazy list of parsed values. If an error occurs, throws an exception.
FromJSON parser
bytestring :: Parser ByteString Source
Match string as a ByteString without decoding the data from UTF8 (strings larger than input chunk, small get always decoded).
Constant space parsers
safeString :: Int -> Parser Text Source
Stops parsing string after the limit is reached. The string will not be matched if it exceeds the size.
number :: Parser Scientific Source
Parse number, return in scientific format.
Convenience aeson-like operators
(.:) :: Text -> Parser a -> Parser a infixr 7 Source
Synonym for objectWithKey
. Matches key in an object.
(.!) :: Int -> Parser a -> Parser a infixr 7 Source
Synonym for arrayWithIndexOf
. Matches n-th item in array.
Structure parsers
objectWithKey :: Text -> Parser a -> Parser a Source
Match only specific key of an object. This function will return only the first matched value in an object even if the source JSON defines the key multiple times (in violation of the specification).
objectItems :: Parser a -> Parser (Text, a) Source
Match all key-value pairs of an object, return them as a tuple. If the source object defines same key multiple times, all values are matched.
objectValues :: Parser a -> Parser a Source
Match all key-value pairs of an object, return only values. If the source object defines same key multiple times, all values are matched. Keys are ignored.
arrayWithIndexOf :: Int -> Parser a -> Parser a Source
Match nith item in an array.
indexedArrayOf :: Parser a -> Parser (Int, a) Source
Match all items of an array, add index to output.
nullable :: Parser a -> Parser (Maybe a) Source
Parses a field with a possible null value. Use defaultValue
for missing values.
Parsing modifiers
defaultValue :: a -> Parser a -> Parser a Source
Returns a value if none is found upstream.