decode is an aeson function that parses a lazy ByteString containing JSON and produces a value whose type has a FromJSON instance. Its result is Maybe a: successful input yields Just a, while invalid JSON or a failed conversion yields Nothing. section 16.1.1
Use decode at the boundary between JSON input and typed Haskell values:
- Decode into the generic Value representation when the JSON structure is not yet mapped to a domain type. section 16.1.1
- Decode directly into a type such as [Int] or TodoEntry when a suitable FromJSON instance is available. section 16.1.1
- Handle Nothing before using the decoded value; malformed JSON and conversion failures do not produce a typed result. section 16.1.1
Decoding a todo entry
After defining a TodoEntry FromJSON instance, decode can turn JSON into a typed value: J.decode "{\"text\":\"Do something\",\"checked\":false}" :: Maybe TodoEntry The result is Just (TodoEntry {entryId = Nothing, text = "Do something", checked = False, rank = Nothing}). A missing required checked field instead produces Nothing when using decode directly. section 16.1.1
Separating JSON decoding from validation
A custom parser can first call decode and then inspect the resulting Value with aeson helpers such as withText or withObject. For example, invalid JSON becomes a parser failure, while valid JSON of the wrong shape reports an expected-type error. section 16.1.1
ghci> import Data.Aeson as J
ghci> :set -XOverloadedStrings
ghci> :i J.Value
type Value :: *
data Value
= Object !Object
| Array !Array
| String !Text
| Number !Scientific
| Bool !Bool
| Null
ghci> J.decode "{\"a\":\"Hello\", \"b\": [1,2,3]}" :: Maybe J.Value
Just (Object (fromList [("a",String "Hello"),("b",Array
[Number 1.0,Number 2.0,Number 3.0])]))
ghci> :t J.decode
J.decode :: FromJSON a => ByteString -> Maybe a
Inspect Value constructors and try decode interactively in GHCi, including decoding an object into Value and checking the inferred type. section 16.1.1
