我在PureScript中有一系列嵌套的配置信息记录,我想传递给JavaScript函数。这些记录主要由Maybe
类型的值组成。有没有一种方法可以将其序列化为JavaScript对象,省略Nothing
- 值方法并展开Just
- 值方法?
我已经taken a shot使用半hacky instanceof
检查在JavaScript中写这个,但它非常痛苦,例如因为没有简单的方法来阻止递归(我无法将我的记录与随机的其他JavaScript对象区分开来)。还有更好的方法吗?
答案 0 :(得分:0)
一种选择是使用purescript-nullable
包。您可以使用Maybe
将Nullable
值转换为toNullable :: forall a. Maybe a -> Nullable a
值。生成的运行时表示适合传递给JavaScript函数,因为toNullable (Just value)
在运行时变为value
,toNullable Nothing
在运行时变为null
。
另一种选择是使用purescript-simple-json
包。您可以使用write :: forall a. WriteForeign a => a -> Foreign
函数将包含Maybe
值的记录转换为Just value
替换为value
且Nothing
替换为{{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