是否可以使用Text.JSON在haskell中创建嵌套的JSON对象?

时间:2013-06-04 15:33:12

标签: json haskell

我有一个结构,它是顶层的一个对象,主要包含字符串作为值和一个嵌套对象。它应该看起来像:

{
  "name" : "expand",
  "type" : "2",
  "code" : "...",
  "options" : {
     "atb" : {
         "description" : "..",
         "value" : true
     }
}

我猜测因为JSObject拥有一个键/值对列表,所以无法在同一级别上混合使用不同的值类型。这似乎是一个巨大的限制,所以我希望我错了!

2 个答案:

答案 0 :(得分:7)

Text.JSON允许您嵌套对象,如the type definition所示:

data JSValue
    = JSNull
    | JSBool     !Bool
    | JSRational !Rational
    | JSString   JSString
    | JSArray    [JSValue]
    | JSObject   (JSObject JSValue)

newtype JSObject e = JSONObject { fromJSObject :: [(String, e)] }

类型是递归的 - JSValues可能是JSObjects,而jSObjects又可能是JSValues的字典。

答案 1 :(得分:1)

如果你还没有使用泛型,那么这是一种使用TEXT.JSON实例的方法

import Text.JSON

data SO = SO {
            name :: String,
            mytype :: Int,
            code :: String,
            options :: [Option]
        } deriving (Show)

data Option =Option {
                atb :: KV
            }


data KV = KV {
                desc :: String,
                v:: Bool
                 }

instance JSON SO where
   showJSON ge = makeObj
          [ ("name", showJSON $ name ge),
            ("type", showJSON $ mytype ge),
            ("options", showJSON $ options ge)
          ]                        
   readJSON = error "readJSON not implemented for SO"


instance JSON Option where
   showJSON ge = makeObj
          [ ("atb", showJSON $ atb ge)
          ]                        
   readJSON = error "readJSON not implemented for Option"

instance JSON KV where
   showJSON ge = makeObj
          [ ("description", showJSON $ desc ge),
          [ ("value", showJSON $ v ge)
          ]                        
   readJSON = error "readJSON not implemented for kv"

- 编码$ SO .........

相关问题