使用包含保留关键字的字段名解析JSON [英] Parse JSON with fieldnames that contain reserved keywords
问题描述
{
data:[$
id:34,
type:link,
story:foo
},
{
id:35,
type:link,
story:bar
}
]
}
由于有很多字段我想忽略,所以我应该使用GHC泛型。但是如何编写一个使用Haskell关键字(如 data
和 type
)的数据类型定义?当然,以下内容给出了:输入数据的解析错误
数据Feed = Feed {data :: [Post]}
deriving(Show,Generic)
data Post = Post {
id :: String,
type: :String,
story :: String
}
deriving(Show,Generic)
ToJSON
实例而不依赖于GHC.Generics。这也意味着您可以对数据表示形式和JSON表示使用不同的字段名称。
{ - #LANGUAGE OverloadedStrings# - }
导入Control.Applicative
导入Data.Aeson
将限定的Data.ByteString.Lazy导入为LBS
数据Post = Post {
postId: :String,
typ :: String,
story :: String
}
派生(显示)
实例FromJSON Post其中
parseJSON (Object x)= Post< $> x。:id*< x .:type< *> x。:story
parseJSON _ = failExpected an Object
实例ToJSON Post其中
toJSON post = object
[id。= postId发布
,type。= typ post
,story。= story post
]
main :: IO()
main =做
打印$(解码$发布{\type \:\myType \,\story \:\真正地介入故事\,\ id \:\SomeId \}::也许发布)
LBS.putStrLn $ encode $发布myIdmyType其他故事
对于Feed也可以做同样的事情。如果您不必忽略字段,则还可以使用 Data.Aeson.TH
中的 deriveJSON
作为第一个参数修改字段名称的函数。
I'm trying to parse the following JSON with aeson.
{
"data": [
{
"id": "34",
"type": "link",
"story": "foo"
},
{
"id": "35",
"type": "link",
"story": "bar"
}
]
}
Since there are a lot of field I'd like to ignore, it seems I should use GHC generics. But how to write a data type definition that uses Haskell keywords like data
and type
? The following of course gives: parse error on input `data'
data Feed = Feed {data :: [Post]}
deriving (Show, Generic)
data Post = Post {
id :: String,
type :: String,
story :: String
}
deriving (Show, Generic)
You can write your own FromJSON
and ToJSON
instances without relying on GHC.Generics. This also means that you can use different field names for the data representation and the JSON representation.
Example instances for Post:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Aeson
import qualified Data.ByteString.Lazy as LBS
data Post = Post {
postId :: String,
typ :: String,
story :: String
}
deriving (Show)
instance FromJSON Post where
parseJSON (Object x) = Post <$> x .: "id" <*> x.: "type" <*> x .: "story"
parseJSON _ = fail "Expected an Object"
instance ToJSON Post where
toJSON post = object
[ "id" .= postId post
, "type" .= typ post
, "story" .= story post
]
main :: IO ()
main = do
print $ (decode $ Post "{\"type\": \"myType\", \"story\": \"Really interresting story\", \"id\" : \"SomeId\"}" :: Maybe Post)
LBS.putStrLn $ encode $ Post "myId" "myType" "Some other story"
The same can be done for Feed. If you didn't have to ignore fields, you could also use deriveJSON
from Data.Aeson.TH
, which takes a function to modify field names as it's first argument.
这篇关于使用包含保留关键字的字段名解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!