Squallcx
Squallcx

Reputation: 125

Aeson Convert Array to Object

What is the best way Data.Aeson FromJSON instance Convert Array to Object:

import Data.Aeson

data MixArray = MixArray {                                                                                                                                                                                         
  vStr :: String,                                                                                                                                                                                                   
  vNum :: Int,
  vBool :: Bool                                                                                                                                                                                                  
} deriving Show   

main = do
  jsonStr = ["a",1,true]
  mix <- eitherDecode $ jsonStr :: IO (Either String [MixArray])
  show mix

to:

MixArray { vStr = "a", vNum = 1, vBool= true}

Upvotes: 0

Views: 197

Answers (1)

castletheperson
castletheperson

Reputation: 33496

You can reuse the FromJSON instance for lists and the Value type, and then construct your type after pattern matching. If the pattern match fails, the parser will fail.

import Data.Text (unpack)

instance FromJSON MixArray where
  parseJSON jsn = do
    [String s, Number n, Bool b] <- parseJSON jsn
    return MixArray { vStr = unpack s, vNum = truncate n, vBool = b }

Upvotes: 1

Related Questions