SumYungGai
SumYungGai

Reputation: 41

JSON output with Haskell

I am trying to use the show function and get back output that looks like JSON The type I have to work with is

data JSON = JNum Double
          | JStr String

I am looking for

JNum 12, JStr"bye", JNum 9, JStr"hi" to return

[12, "bye", 9, "hi"]

I have attempted:

instance Show JSON where
  show ans = "[" ++ ans ++ "]"

but fails with a compile error. I have also tried

instance Show JSON where
  show ans = "[" ++ ans ++ intercalate ", " ++ "]"

but failed with "Not in scope: data constructor 'JSON' Not sure how to use "ans" to represent whatever type JSON receives as input in the ouput, be it a string, double..etc... Not very good with Haskell so any hints would be great.

Thx for reading

Upvotes: 2

Views: 249

Answers (2)

ErikR
ErikR

Reputation: 52039

You can have GHC automatically derive a show function for you by adding deriving (Show) to your data declaration, e.g.:

data JSON = ... deriving (Show)

As for your code, in order for show ans = "[" ++ ans ++ "]" to type check ans needs to be a String, but ans has type JSON.

To write your own show function you have to write something like:

instance Show JSON where
   show (JNum d) = ... code for the JNum constructor ...
   show (JObj pairs) = ... code for the JObj constructor ...
   show (JArr arr) = ... code for the JArr constructor ...
   ...

Here d will have type Double, so for the first case you might write:

   show (JNum d) = "JNum " ++ show d

or however you want to represent a JSON number.

Upvotes: 2

Sibi
Sibi

Reputation: 48664

If you want to write your own instance, you can do something like this:

instance Show JSON where
  show (JNum x) = show x
  show (JStr x) = x
  show (JObj xs) = show xs
  show (JArr xs) = show xs

Note that for JObj and JArr data constructor, the show will use the instance defined for JObj and JArr.

Demo:

λ> JArr[JNum 12, JStr"bye", JNum 9, JStr"hi"] 
[12.0,bye,9.0,hi]

Upvotes: 1

Related Questions