In Haskell, we can use the aeson library for JSON encoding and decoding. This library provides built-in support for working with JSON data, including custom data types.
First, let’s import the necessary modules:
We’ll define two data types to demonstrate encoding and decoding of custom types:
Now, let’s look at encoding basic data types to JSON:
For slices and maps, which encode to JSON arrays and objects:
Now, let’s encode our custom data types:
For decoding JSON data into Haskell values:
In Haskell, we don’t have a direct equivalent to Go’s json.NewEncoder. However, we can achieve similar functionality by using B.hPutStrLn:
This Haskell code demonstrates JSON encoding and decoding using the aeson library. It covers basic data types, custom types, and working with more complex nested structures. The aeson library provides a powerful and flexible way to work with JSON in Haskell, with support for automatic derivation of JSON instances for many types.