Alexandre Rademaker
Alexandre Rademaker

Reputation: 2813

haskell record parameter or alternative

I am using aeson for parsing a https://jsonlines.org/ files. Those files are dumps of Elastic Search indexes so the outermost structure is the same in all JSON objects. If I understood right, record syntax do not allow parameter like in the Document record below, right? What would be the alternative?

One possible solution would be to use the JSON AST to read the JSON innermost objects and parse them latter, is it possible? How?


import Data.Aeson
import qualified Data.ByteString.Lazy as L
import Data.Either
import Data.List
import GHC.Generics


data Suggestion =
  Suggestion { ... }
  deriving (Show, Generic)

data Synset =
  Synset { ...}
  deriving (Show, Generic)

data Document a =
  Document a
    { _index :: String
    , _type :: String
    , _id :: String
    , _score :: Int
    , _source :: a
    }
  deriving (Show, Generic)

readJ :: L.ByteString -> Either String Document
readJ s = eitherDecode s :: Either String Document

readJL :: FilePath -> IO [Either String Document]
readJL path = do
  content <- L.readFile path
  return (map readJ $ L.split 10 content)

Upvotes: 0

Views: 242

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80754

Yes, record syntax does allow type parameters, you just shouldn't repeat them after the constructor name:

data Document a =
  Document
    { _index :: String
    , _type :: String
    , _id :: String
    , _score :: Int
    , _source :: a
    }
  deriving (Show, Generic)

Upvotes: 1

Related Questions