json-spac
Members list
Packages
This package provides extensions to the core "spac" library which allow for the handling of JSON data.
This package provides extensions to the core "spac" library which allow for the handling of JSON data.
Rather than creating explicit classes that extend Parser
, Transformer
, and Splitter
, this package provides type aliases and implicit extensions. For example, JsonParser[A]
is just a type alias for Parser[JsonEvent, A]
, and JsonParser
is just a call to Parser[JsonEvent]
.
Implicit JsonParsers are available for each of the JSON primitive types:
string
number
(expressed asInt
,Long
,Float
, orDouble
)boolean
null
(expressed asNone.type
)
Helpers are available for parsing JSON arrays and objects:
JsonParser.listOf[A]
to parse anarray`` where each value is an
A`JsonParser.objectOf[A]
to parse anobject
where the value for each field anA
JsonParser.objectOfNullable[A]
to parse anobject
where the value for each field is eithernull
or anA
, filtering out thenull
sJsonParser.fieldOf[A](fieldName)
to parse a specific field from an object
A DSL for creating json-specific ContextMatchers is provided to make it more convenient to call Splitter.json
. For example:
Splitter.json("foo" \ "bar").as[String].parseFirst
Can be used to capture rootJson.foo.bar
as a String in
{
"foo": {
"bar": "hello"
}
}
To "split" values inside arrays, index-related context matchers are available, e.g.
Splitter.json("foo" \ anyIndex).as[Int].parseToList
Can be used to capture each of the numbers in the "foo" array in
{
"foo": [1, 2, 3]
}
A note about JsonEvents in spac: JSON doesn't have any explicit markers for when a field ends, or when an array index starts or ends; those context changes are essentially inferred by the presence of some other event. For example, instead of a "field end" event, typically there will be either a new "field start" or a token representing the end of the current object. With spac, splitters and context matchers generally operate under the assumption that a "stack push" event (like a field start) will eventually be followed by a corresponding "stack pop" event (i.e. field end).
To allow for this, these "inferred" events (FieldEnd, IndexStart, IndexEnd) are explicitly represented as JsonEvents in the stream being parsed. Keep this in mind when creating JSON ContextMatchers:
field
-related matchers will match a stack likecase ObjectStart :: FieldStart(_) :: _
index
-related matchers will match a stack likecase ArrayStart :: IndexStart(_) :: _