Exporting data as JSON
A convenient way to store data that may not adhere to a strict schema is through JSON. To accomplish this, we will use a painless JSON library called Yocto. It sacrifices performance for readability and small size.
In this recipe, we will export a list of points as JSON.
Getting ready
Install the Yocto JSON encoder and decoder from cabal using the following command:
$ cabal install yocto
How to do it…
Start by creating a new file, which we call Main.hs
and perform the following steps:
- Import the relevant data structures, as shown in the following code:
import Text.JSON.Yocto import qualified Data.Map as M
- Define a data structure for 2D points:
data Point = Point Rational Rational
- Convert a
Point
data type into a JSON object, as shown in the following code:pointObject (Point x y) = Object $ M.fromList [ ("x", Number x) , ("y", Number y)]
- Create the points and construct a JSON array out of them:
main = do let points = [ Point...