2

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.

2
  • 1
    That string is a JSON array. It's not an object. A JSON object would look like this: { "a": "hello", "b": 3, "c": 2, "d": "world", "e": [1, 3, 5] } Commented Jul 1, 2019 at 12:44
  • Will this help? github.com/chrisdone/dynamic Commented Jul 1, 2019 at 13:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.