Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Import the relevant data structures, as shown in the following code:

    import Text.JSON.Yocto
    import qualified Data.Map as M
  2. Define a data structure for 2D points:

    data Point = Point Rational Rational
  3. 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)]
  4. Create the points and construct a JSON array out of them:

    main = do
      let points = [ Point 1 1
                   , Point...