从嵌套记录中解开Maybe值

时间:2018-06-13 05:03:48

标签: purescript

我在PureScript中有一系列嵌套的配置信息记录,我想传递给JavaScript函数。这些记录主要由Maybe类型的值组成。有没有一种方法可以将其序列化为JavaScript对象,省略Nothing - 值方法并展开Just - 值方法?

我已经taken a shot使用半hacky instanceof检查在JavaScript中写这个,但它非常痛苦,例如因为没有简单的方法来阻止递归(我无法将我的记录与随机的其他JavaScript对象区分开来)。还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

一种选择是使用purescript-nullable包。您可以使用MaybeNullable值转换为toNullable :: forall a. Maybe a -> Nullable a值。生成的运行时表示适合传递给JavaScript函数,因为toNullable (Just value)在运行时变为valuetoNullable Nothing在运行时变为null

另一种选择是使用purescript-simple-json包。您可以使用write :: forall a. WriteForeign a => a -> Foreign函数将包含Maybe值的记录转换为Just value替换为valueNothing替换为{{1}的记录}}。对于具有undefined值的嵌套记录的用例,此方法应该更直接。

答案 1 :(得分:0)

您可以使用Data.Argonaut中的genericEncodeJson并将omitNothingFields标记设置为true。这个标志正是你所期望的。

module Main where

import Prelude

import Control.Monad.Eff.Console (logShow)
import Data.Argonaut.Generic.Aeson (options)
import Data.Argonaut.Generic.Encode (Options(..), genericEncodeJson)
import Data.Generic (class Generic)
import Data.Maybe (Maybe(..))

data TheRecord = TheRecord { a :: Maybe Int, b :: Maybe String, c :: String }
derive instance gRecord :: Generic TheRecord

main = 
    -- Prints {"c":"Always here","a":42}
    logShow $ genericEncodeJson (Options o { omitNothingFields = true }) rec
    where
        rec = TheRecord { a: Just 42, b: Nothing, c: "Always here" }
        Options o = options