Correctly Parsing a JSON Array as Custom Data Type Object

Viewed 199

I defined the following datatype object in Haskell:

import GHC.Generics
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

data DLA = DLA {
                a::String,
                b::Int,
                c::Int,
                d::String,
                e::[Int]
                } deriving (Show, Generic)

instance FromJSON DLA
instance ToJSON DLA

And receive a json array from some frontend-application in the following format

[\"hello\",3,2,\"world\",[1,3,5]]

When I tried to parse this like

decode $ C.pack "[\"hello\",3,2,\"world\",[1,3,5]]"::Maybe DLA

it simply returned Nothing. Trying to pass it more general like

decode $ C.pack "[\"hello\",3,2,\"world\",[1,3,5]]"::Maybe Value

returned the following output:

Just (Array [String "hello",Number 3.0,Number 2.0,String "world",Array [Number 1.0,Number 3.0,Number 5.0]])

So the problem seems to be that Haskell interprets the string as an array, not an object, and thus rightly throws an exception. Any ideas how to fix this?

I am using the current version of ghc and ghci, and Data.Aeson for this.

1 Answers

I found a solution which is quite simple using pattern matching but more direct approaches are also welcome, as I believe there should be some functionality for this.

raw = fromJust (decode $ C.pack "[\"hello\",3,2,\"world\",[1,3,5]]"::Maybe (String, Int, Int,   String, [Int]))

func::(String, Int, Int, String, [Int]) -> DLA
func (a,b,c,d,e) = DLA a b c d e
Related