12

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

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

        }
    }

}

哪里A, B,C提前是未知的。这三个人中的每一个也可能有兄弟姐妹。

我想知道是否有一种方法可以用 Aeson 以某种优雅的方式将其解析为自定义类型。我一直在做的是将它加载到 AesonObject中。

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

谢谢!

编辑

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

这应该编译到CountryDatabase哪里......

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

1 回答 1

18

You can reuse FromJSON instance of Map String v. Something like the next:

{-# 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)

The output:

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: You can do it without newtypes, I used them only for clarity.

于 2013-06-24T18:12:48.150 回答