简体   繁体   English

Haskell的JSON输出

[英]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 我正在尝试使用show函数并获取类似JSON的输出,我必须使用的类型是

data JSON = JNum Double
          | JStr String

I am looking for 我在寻找

JNum 12, JStr"bye", JNum 9, JStr"hi" to return JNum 12,JStr“ bye”,JNum 9,JStr“ hi”返回

[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. 但由于“不在范围内:数据构造器'JSON'而失败”不知道如何使用“ ans”来表示JSON在输出中作为输入接收的任何类型,可以是字符串,也可以是double..etc ...对于Haskell不太好所以任何提示都会很棒。

Thx for reading 阅读Thx

You can have GHC automatically derive a show function for you by adding deriving (Show) to your data declaration, eg: 您可以通过在数据声明中添加deriving (Show)来使GHC为您自动派生一个show函数,例如:

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. 至于您的代码,为了使show ans = "[" ++ ans ++ "]"键入check, ans必须是String,但是ans具有JSON类型。

To write your own show function you have to write something like: 要编写自己的show函数,您必须编写如下内容:

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: 此处d类型为Double,因此对于第一种情况,您可以编写:

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

or however you want to represent a JSON number. 或者您想代表一个JSON数字。

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 . 请注意,对于JObjJArr数据构造函数,该节目将使用为JObjJArr定义的实例。

Demo: 演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM