首页 > 解决方案 > 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)

标签: jsonhaskellaeson

解决方案


是的,记录语法确实允许类型参数,您只是不应该在构造函数名称之后重复它们:

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

推荐阅读