Using file name in json parsing (Haskell Aeson)

I have no experience at Haskell. I am trying to parse many files .jsonin a data structure in Haskell using aeson . However, for reasons beyond my control, I need to save the name of the file from which the data was analyzed as one of the fields in my data. A simple example of what I have so far:

data Observation = Observation { id :: Integer
                               , value :: Integer
                               , filename :: String}

instance FromJSON Observation where
  parseJson (Object v) =
    Observation <$> (read <$> v .: "id")
                <*> v .: "value"
                <*> ????

My question is: what is a smart way to serialize my data when parsing a json file with access to the file name?

What comes to my mind - is to identify one datalike NotNamedObservation, initialize it, and then have a function that converts NotNamedObservation -> String -> Observation(where String - the file name), but it sounds very bad. p>

Thank.

+4
2

:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import qualified Data.ByteString.Lazy as LBS
import System.Environment

data Observation = Observation { ident    :: Integer
                               , value    :: Integer
                               , filename :: FilePath
                               } deriving (Show)

instance FromJSON (FilePath -> Observation) where
  parseJSON (Object v) =
    do i <- read <$> v .: "id"
       l <- v .: "value"
       pure $ Observation i l

main :: IO ()
main = do
  files <- getArgs
  fileContents <- traverse LBS.readFile files
  print fileContents
  let fs = map (maybe (error "Invalid json") id . decode) fileContents
      jsons :: [Observation]
      jsons = zipWith ($) fs files
  print jsons
0

data , (de) .

, FromJSON/ToJSON .

, (, , parseJSON ToJSON) , JSON Haskell.


- - , , , undefined . , "" ( , ), , .


data Observation' p = Observation
  { id :: Integer
  , value :: Integer
  , filename :: p String }

-- This is isomorphic to the original Observation data type
type Observation = Observation Identity

-- When we don't have the filename available, we keep the field empty with Proxy
instance FromJSON (Observation' Proxy) where
  ...

mkObservation :: FileName -> Observation' Proxy -> Observation
+1

Source: https://habr.com/ru/post/1696364/


All Articles