Reputation: 125
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
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