如何在Yesod中操纵json中的数据?

时间:2018-02-23 14:27:46

标签: haskell yesod

如果我有这段代码,如何更改发布请求发送的JSON的年龄然后返回?我对Haskell的总体体验非常糟糕,所以,我不知道我的问题是否源于语言本身的Yesod框架中缺乏知识。

{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies          #-}

module Handler.Home where
import Data.Aeson
import Data.Text (Text)
import Yesod


data HelloWorld = HelloWorld

mkYesod "HelloWorld" [parseRoutes|
/ HomeR GET POST
|]

instance Yesod HelloWorld

data Person = Person
    { name :: Text
    , age :: Int
    } deriving (Eq, Show)

instance ToJSON Person where
    toJSON (Person n a)  = object
        [ "name" .= n
        , "age"  .= a
        ]

instance FromJSON Person where
    parseJSON = withObject "Person" $ \v -> Person
        <$> v .: "name"
        <*> v .: "age"

getHomeR :: Handler Value
getHomeR = returnJson $ Person "Rafael" 21


postHomeR :: Handler Value
postHomeR = do
    json_payload <- requireJsonBody :: Handler Person
    returnJson json_payload

main :: IO ()
main = warp 3000 HelloWorld

1 个答案:

答案 0 :(得分:2)

json_payloadPerson,因此您只需使用记录更新语法即可 例如,值json_payload { age = 32 }包含json_payload的所有字段,但age字段除外。

因此,您可以将postHomeR重写为

postHomeR = do
  json_payload <- requireJsonBody :: Handler Person
  let modified = json_payload { age = 32 }
  returnJson modified

或者

postHomeR = do
  json_payload <- requireJsonBody :: Handler Person
  returnJson (json_payload { age = 32 })

括号不是必需的,但我认为它更清晰,而不必去检查优先级的语法规则。