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 as Int, Long, Float, or Double)
  • boolean
  • null (expressed as None.type)

Helpers are available for parsing JSON arrays and objects:

  • JsonParser.listOf[A] to parse an array`` where each value is anA`
  • JsonParser.objectOf[A] to parse an object where the value for each field an A
  • JsonParser.objectOfNullable[A] to parse an object where the value for each field is either null or an A, filtering out the nulls
  • JsonParser.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 like case ObjectStart :: FieldStart(_) :: _
  • index-related matchers will match a stack like case ArrayStart :: IndexStart(_) :: _

Attributes

In this article