我想解析哈希Kell中的JSON數據。經歷了大量的網站,這是我所能達到的最遠的地方。JSON解析哈斯克爾
data Address = Address { house :: Integer, street :: String, city :: String, state :: String, zip :: Integer } deriving (Show)
data Person = Person { name :: String, age :: Integer, address :: Address } deriving (Show)
getName :: Person -> String
getName (Person n _ _) = n
getAddress :: Person -> Address
getAddress (Person _ _ a) = a
getState :: Address -> String
getState (Address _ _ _ s _) = s
我寫在文件中ex.hs並加載它在ghci中 - >
Prelude> import Text.JSON
Prelude Text.JSON> :load ex
Main Text.JSON> let aa = "{\"name\": \"some body\", \"age\" : 23, \"address\" : {\"house\" : 285, \"street\" : \"7th Ave.\", \"city\" : \"New York\", \"state\" : \"New York\", \"zip\" : 10001}}"
...> decode aa :: Result JSValue
它返回
Ok (JSObject (JSONObject {fromJSObject = [("name",JSString (JSONString {fromJSString = "some body"})),("age",JSRational False (23 % 1)),("address",JSObject (JSONObject {fromJSObject = [("house",JSRational False (285 % 1)),("street",JSString (JSONString {fromJSString = "7th Ave."})),("city",JSString (JSONString {fromJSString = "New York"})),("state",JSString (JSONString {fromJSString = "New York"})),("zip",JSRational False (10001 % 1))]}))]}))
不用說,它似乎相當冗長(和可怕)。我試過
...> decode aa :: Result Person
它給了我一個錯誤。我如何去從這個json字符串填充Person數據結構的實例?例如,我應該怎麼做才能的人的狀態的JSON字符串...
也許你也應該舉一個例子來創建一個JSON實例,因爲你提到它作爲一種替代方案。 – Wes
@韋斯,你走了。 – sabauma
非常有用的信息。我有個問題。除了'Text.JSON.Generic'(這個包是從哪裏來的?),我還發現https://hackage.haskell.org/package/generic-aeson類似地使用泛型機制來生成Haskell的JSON實例數據。這兩個軟件包有什麼區別? –