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
