如何将Nothing映射到Elm Json.Decoder?

时间:2017-01-12 22:06:48

标签: json elm

这是Elm v0.18的问题

我有

type alias Header =
    { value : String
    , term : Maybe String
    }

我需要用Json.Decode Decoder填充它。但是,JSON中仅存在valueterm我需要指定Nothing

我能够通过将Json.Decode.maybe与不存在的字段一起使用,以一种hackish方式构建解码器:

import Json.Decode exposing (map2, field, string, maybe)

map2 Header (field "header" string)
  (maybe (field "no_such_field" string))

生成Decoder Nothing值的“正确”方法是什么?

2 个答案:

答案 0 :(得分:2)

https://jsfiddle.net/b80sa4kx/可用于在解码器中包装常量值:

map2 Header (field "header" string)
    (succeed Nothing)

答案 1 :(得分:1)

最简单的方法是只使用一个只带一个参数的匿名函数,"标题",并且总是填写var thisArg = { custom: 'object' }; var globalVar = 'global'; productLineSelect.addEventListener('change', function(event) { var localVar = 'local'; getSelection(event, this, globalVar, localVar); }.bind(thisArg), false); 这个词:

Nothing

或等效

map (\header -> Header header Nothing) (field "header" string)