How to use json library?

I am trying to figure out the Haskell json library . However, I ran into a problem in ghci:

Prelude> import Text.JSON
Prelude Text.JSON> decode "[1,2,3]"

<interactive>:1:0:
    Ambiguous type variable `a' in the constraint:
      `JSON a' arising from a use of `decode' at <interactive>:1:0-15
    Probable fix: add a type signature that fixes these type variable(s)

I think this has something to do with a in a type signature:

decode :: JSON a => String -> Result a

Can someone show me:

  • How to decode a string?
  • What happens to the type system here?
+5
source share
3 answers

You need to specify which type you want to return, for example:

decode "[1,2,3]" :: Result [Integer]
-- Ok [1,2,3]

If this line was part of a larger program in which you could continue and use the result decode, the type could simply be inferred, but since ghci does not know which type you need, it cannot output it.

, read "[1,2,3]" .

+7

:

decode :: JSON a => String -> Result a

, . :

userAge :: String -> Int
userAge input = case decode input of
                  Result a -> a
                  _ -> error $ "Couldn't parse " ++ input

userAge typechecker , Result Int.

, decode GHCi, , :

decode "6" :: Result Int
=> Ok 6
+4

A quick look at the documents seems to suggest that the purpose of this function is to allow you to read JSON into any Haskell data structure of a supported type, therefore

decode "[1, 2, 3]" :: Result [Int]

must work

+2
source

All Articles