JSON output with Haskell

by SumYungGai   Last Updated April 15, 2019 11:26 AM - source

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

Tags : json haskell

Answers 2

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.

January 31, 2015 18:08 PM

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.


λ> JArr[JNum 12, JStr"bye", JNum 9, JStr"hi"] 
January 31, 2015 18:09 PM

Related Questions

AESON: Parse dynamic structure

Updated July 03, 2017 14:26 PM

How to create data processing pipeline with Haskell

Updated January 30, 2018 15:26 PM

FromJSON [Object] implementation

Updated June 10, 2017 10:26 AM