liveBook · Manning

JSON value

As explained in Learn Haskell by Example

Value is aeson's Haskell data type representing any possible JSON value.

A JSON value is aeson's Haskell representation of any possible JSON value. The Value type has six forms: Object, Array, String, Number, Bool, and Null. GHCi can decode JSON text into Maybe Value, allowing JSON structure to be inspected directly. section 16.1.1

Use JSON values as the intermediate representation between JSON data and typed Haskell values:

  • Decode a lazy ByteString with decode, whose FromJSON constraint determines the target type. section 16.1.1
  • Convert ordinary Haskell values into Value with toJSON, including strings, numbers, and Booleans. section 16.1.2
  • Construct object values with object and key-value pairs made with (.=). section 16.1.2
  • Parse a Value into a domain type with helpers such as withObject, withText, withArray, withScientific, and withBool. section 16.1.1

Inspecting and parsing JSON values

The JSON object {"a":"Hello", "b":[1,2,3]} decodes to an Object containing a String and an Array of Number values. A parser using withText accepts a JSON string but reports an error when given a Number. A TodoEntry parser instead uses withObject, reads required fields with (.:), and reads optional fields with (.:?).

Value also supports serialization: ToJSON turns a Haskell value into a Value, and encode turns that Value into JSON bytes. Defining matching ToJSON and FromJSON instances enables a round trip between a TodoEntry and its JSON representation. section 16.1.2

How Learn Haskell by Example covers it

How deep it goes
Defines six constructors and demonstrates typed parser helpers, while deferring broader JSON-processing concerns.
Examples
Demonstrates objects, arrays, primitive values, text-parser errors, TodoEntry parsing, and encode-decode round trips.
What it assumes
Uses Haskell values, type classes, GHCi, and lazy ByteString while introducing the Value representation through examples.
What you can do after
Build JSON parsers and serializers by inspecting Value constructors and defining FromJSON and ToJSON instances.
How it connects
Connects Value to Aeson, JSON parsing, FromJSON, ToJSON, Parser, decode, encode, and lazy ByteString.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.