liveBook · Manning

JSON array

As explained in Functional Programming in Scala, Second Edition

A JSON array is an ordered JSON value containing a comma-separated sequence of JSON values enclosed in square brackets.

A JSON array is an ordered value containing comma-separated JSON values inside square brackets. Its elements may be literals, objects, or nested arrays. section 9.4.1

A parser for JSON arrays makes the structure explicit:

  • Consumes an opening square bracket, parses a value, and repeats separator–value pairs. section 9.8
  • Allows an empty array by choosing between one-or-more separated values and an empty result. section 9.8
  • Discards commas and converts the parsed list into an IndexedSeq stored by JArray. section 9.8
  • Handles surrounding whitespace with token parsers and adds array context to parse failures. section 9.8

A nested array value

The Related companies field contains ["HPQ", "IBM", "YHOO", "DELL", "GOOG"]. A parser represents these ordered strings as a JArray, while the surrounding document remains a JObject. section 9.4.1

def token(s: String): Parser[String] =
  string(s).attempt <* whitespace
 
def array: Parser[JSON] =
  token("[") *> value.sep(token(",")).map(vs =>
    JArray(vs.toIndexedSeq)) <* token("]")

This implementation shows the array grammar after whitespace has been incorporated: tokens surround the brackets and commas, while value.sep collects the elements. section 9.8

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the grammar and implements whitespace, separators, recursion, and scoped errors, without describing later semantic processing.
Examples
Uses a related-companies list of ticker strings and Scala definitions for JArray, sep, token, and scope.
What it assumes
Assumes JSON grammar and parser-combinator concepts while deriving separated repetition and token handling through implementation.
What you can do after
Builds a JSON-array parser that accepts empty or nonempty arrays, nested values, whitespace, and trailing-input checks.
How it connects
Connects JSON arrays with JSON values, JSON objects, parser combinators, whitespace handling, and parse errors.

Also explained in

Compare how 3 books explain JSON array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.