liveBook · Manning

Encode

As explained in Learn Haskell by Example

encode is an aeson function that serializes a value with a ToJSON instance into JSON represented as a ByteString.

encode is an aeson function that serializes a value with a ToJSON instance into JSON held in a lazy ByteString. Use toJSON when you need the intermediate JSON Value instead. section 16.1.1 section 16.1.2

A typical serialization workflow is:

  • Define a ToJSON instance for the type you want to serialize. section 16.1.1
  • Use toJSON to construct a JSON Value when working with JSON structure directly. section 16.1.2
  • Call encode to produce the serialized JSON ByteString. section 16.1.1

Serializing a list and a record

ghci> J.encode ([1,2,3] :: [Int]) "[1,2,3]" For a custom TodoEntry, a ToJSON instance builds an object from fields with object and .=; then J.encode e produces JSON such as {"checked":false,"entryId":null,"rank":1,"text":"Do Something"}. section 16.1.2

ghci> J.decode "[1,2,3]" :: Maybe [Int]
Just [1,2,3]
ghci> J.encode ([1,2,3] :: [Int])
"[1,2,3]"
ghci> :t J.encode
J.encode :: ToJSON a => a -> ByteString

Inspect encode's inferred type and a complete GHCi example for serializing a list. section 16.1.1

How Learn Haskell by Example covers it

How deep it goes
Defines encode's type and use, then works through custom object serialization without covering its implementation internals.
Examples
Demonstrates encoding [1,2,3] and a TodoEntry whose fields are serialized through a custom ToJSON instance.
What it assumes
Assumes a Haskell value and ToJSON support, while introducing JSON Value construction and record instances through examples.
What you can do after
Apply it via aeson to serialize lists and custom records into JSON ByteStrings.
How it connects
Connects encode with ToJSON, toJSON, JSON Value, decode, FromJSON, and 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.