Casper Thule Hansen
Casper Thule Hansen

Reputation: 1550

Convert JSON value field with aeson

Scenario: I need to read in a JSON file and then update the value field within abcs to an absolute path.

The keys related to the value fields are not static, and therefore I would like to perform it using the hashmaps.

My challenge is, that I keep going round and round in the types and cannot figure out how to convert them. Ideally, updatePaths should return IO Object.

JSON:

{
    "abcs": {
        "{crtl}": "crtl.abc",
        "{wt}": "wt.abc"
    }
}

Haskell:

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module TCT.ScenarioRunner where
import Network.HTTP.Simple
import Data.Aeson
import GHC.Generics
import qualified Data.ByteString.Lazy as B
import qualified Data.HashMap.Strict as Hm
import Data.Text.Internal
import Filesystem.Path
import System.Path.NameManip (absolute_path)

loadFile :: IO B.ByteString
loadFile = B.readFile "resources/initialise_body.json"

initialise :: String -> IO ()
initialise sessionId = do
  raw <- loadFile
  let json = (eitherDecode raw) :: Either String Value
  case json of
        Left err -> putStrLn err
        Right (Object ps) -> 
          case Hm.lookup "abcs" ps of
            Nothing -> putStrLn "Could not find abcs"
            Just (Object abcs) -> do
              (putStrLn "Found abcs")
              result <- print $ updatePaths abcs
              putStrLn "Bla"
  putStrLn "TBD: initialise"

updatePaths :: Object -> Object
updatePaths obj = Hm.map createFullPath obj
  where createFullPath val = absolute_path ("resources/abcs/" ++ val)

Error:

src/TCT/ScenarioRunner.hs:71:22-46: error: …
    • Couldn't match type ‘IO String’ with ‘Value’
      Expected type: Object
        Actual type: Hm.HashMap Text (IO String)
    • In the expression: Hm.map createFullPath obj
      In an equation for ‘updatePaths’:
          updatePaths obj
            = Hm.map createFullPath obj
            where
                createFullPath val = absolute_path ("resources/abcs/" ++ val)
   |
src/TCT/ScenarioRunner.hs:71:44-46: error: …
    • Couldn't match type ‘Value’ with ‘[Char]’
      Expected type: Hm.HashMap Text [Char]
        Actual type: Object
    • In the second argument of ‘Hm.map’, namely ‘obj’
      In the expression: Hm.map createFullPath obj
      In an equation for ‘updatePaths’:
          updatePaths obj
            = Hm.map createFullPath obj
            where
                createFullPath val = absolute_path ("resources/abcs/" ++ val)
   |
Compilation failed.

Update: Probies solution is almost correct, I made a few changes, so the solution becomes:

 updatePaths :: Object -> IO Object
 updatePaths (obj :: Object) = traverse createFullPath obj
  where
    createFullPath :: Value -> IO Value
    createFullPath (String val) =
      (String . T.pack) <$> absolute_path ("resources/abcs/" ++ (T.unpack val))
    createFullPath x = pure x -- Ignore non strings

Update 2: In order to understand the solution better I looked at the traverse type signature. Traverse has the type signature: ... => (a -> f b) -> t a -> f (t b)

a must be Value;

f must be IO;

t must be HashMap Text, as Object is a type synonym for HashMap Text Value

This gives us: (Value -> IO Value) -> HashMap Text Value -> IO (HashMap Text Value) or IO Object as desired.

Upvotes: 1

Views: 336

Answers (1)

Probie
Probie

Reputation: 1361

There are a couple of issues. Firstly, you have a HashMap of Aeson Value, not String so we need to pattern match to get out our "String". Secondly the "String type" Aeson uses is Text, whilst absolute_path wants a regular string, so we'll need to do some conversion. Third, absolute_path will return an IO value, so we'll need to use traverse instead of a map.

So, assuming you've already imported Data.Text as T

updatePaths :: Object -> IO Object
updatePaths obj = traverse createFullPath obj
  where 
    createFullPath (String val) = 
      (String . T.pack) <$> absolute_path ("resources/abcs/" ++ (T.unpack val))
    createFullPath x = pure x -- Ignore non strings

Upvotes: 1

Related Questions