M
M
mirexdoors2021-02-11 10:38:53
Haskell
mirexdoors, 2021-02-11 10:38:53

How to correctly declare types when parsing json?

Hello, I'm new to Haskell! The task is as follows: I get a list from json in the following way.

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
import Data.Aeson
import qualified Data.ByteString.Lazy as B
import GHC.Generics

data DayHealthItem = DayHealthItem { summary_date :: String,
                                     period_id :: Int,
                                     is_longest :: Int,
                                     timezone :: Int
                                  } deriving (Generic, Show)

instance FromJSON DayHealthItem

main = do
  input <- B.readFile "mock/data.json"
  let maybeDecodedJSON = decode input :: Maybe [DayHealthItem]
  case maybeDecodedJSON of
    Nothing -> error "error parsing JSON"
    Just decodedJSON -> (putStrLn.show) decodedJSON

The question is how can I correctly declare the types so that I can then manage this data, that is, apply all the list functions to them, because if I do something like this in the last line:

...
    Just decodedJSON -> (putStrLn.head) decodedJSON

then I get an error:
Couldn't match type ‘DayHealthItem’ with ‘[Char]’
      Expected type: [String]
        Actual type: [DayHealthItem]

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question