与Aeson - Haskell的任意JSON密钥

时间:2013-06-24 14:51:29

标签: json haskell aeson

我有一堆带有任意键的嵌套JSON对象。

{
    "A": {
        "B": {
            "C": "hello"

        }
    }

}

ABC提前未知的地方。这三者中的每一个也可以 有兄弟姐妹。

我想知道是否有办法将此解析为Aeson中的自定义类型 一些优雅的方式。我一直在做的是将它加载到Aeson Object

您将如何为这种JSON实现FromJSON 对象

谢谢!

修改

{
    "USA": {
        "California": {
            "San Francisco": "Some text"
        }
    },
    "Canada": {
        ...
    }
}

这应编译到CountryDatabase其中......

type City            = Map String String
type Country         = Map String City
type CountryDatabase = Map String Country 

1 个答案:

答案 0 :(得分:18)

您可以重复FromJSON Map String v个实例。像下一个:

{-# LANGUAGE OverloadedStrings #-}

import Data.Functor
import Data.Monoid
import Data.Aeson
import Data.Map (Map)
import qualified Data.ByteString.Lazy as LBS
import System.Environment

newtype City = City (Map String String)
  deriving Show

instance FromJSON City where
  parseJSON val = City <$> parseJSON val

newtype Country = Country (Map String City)
  deriving Show

instance FromJSON Country where
  parseJSON val = Country <$> parseJSON val

newtype DB = DB (Map String Country)
  deriving Show

instance FromJSON DB where
  parseJSON val = DB <$> parseJSON val

main :: IO ()
main = do
  file <- head <$> getArgs
  str <- LBS.readFile file
  print (decode str :: Maybe DB)

输出:

shum@shum-lt:/tmp/shum$ cat in.js 
{
    "A": {
        "A1": {
            "A11": "1111",
            "A22": "2222"
        }
    },
    "B": {
    }
}
shum@shum-lt:/tmp/shum$ runhaskell test.hs in.js 
Just (DB (fromList [("A",Country (fromList [("A1",City (fromList [("A11","1111"),("A22","2222")]))])),("B",Country (fromList []))]))
shum@shum-lt:/tmp/shum$

PS:你可以在没有newtype的情况下完成,我只是为了清楚起见而使用它们。