liveBook · Manning

Aeson

As explained in Learn Haskell by Example

aeson is a Haskell library for encoding and decoding JSON data.

aeson is a Haskell library for converting JSON data to and from typed Haskell values. It fits naturally into a type-safe HTTP/JSON API: define an application type, provide JSON instances, and use decode for input and encode for output. section 16.0 section 16.1.1

The central API uses two typeclasses and a JSON representation:

  • FromJSON defines parsing, while ToJSON defines serialization. Generic can automatically derive implementations based on a datatype definition. section 16.4

Parsing a todo entry

A todo application can model an entry as `TodoEntry { entryId :: Maybe Int, text :: Text, checked :: Bool, rank :: Maybe Int }`. Its parser accepts an object, reads optional `entryId` and `rank` fields with `.:?`, and requires `text` and `checked` with `.:`. The parser can then become the `FromJSON` implementation: `instance J.FromJSON TodoEntry where parseJSON = todoEntryParser`. Missing optional fields become `Nothing`, while a missing required field produces an error.

How Learn Haskell by Example covers it

How deep it goes
Descends from decode and encode to custom object parsers, required fields, optional fields, errors, and FromJSON instances.
Examples
Uses GHCi values, lists of integers, and a TodoEntry parser with required text and checked fields.
What you can do after
Build typed JSON parsers and serializers by defining data types and implementing or deriving ToJSON and FromJSON.
How it connects
Connects JSON values with Haskell data types, typeclasses, Generic deriving, HTTP APIs, and database-backed applications.

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.