解码列表时是否可以忽略无效项目?\n示例:我有一个模型
\ntype Type\n = A\n | B\n\ntype alias Section =\n { sectionType : Type\n , index : Int\n }\n\n\ngetTypeFromString : String -> Maybe Type\ngetTypeFromString input =\n case input of\n \xe2\x80\x9ca\xe2\x80\x9d ->\n Just A\n\n \xe2\x80\x9cb\xe2\x80\x9d ->\n Just B\n\n _ ->\n Nothing\n\ndecodeType : Decoder Type\ndecodeType =\n Decode.string\n |> Decode.andThen\n (\\str ->\n case getTypeFromString str of\n Just sectionType ->\n Decode.succeed sectionType\n\n Nothing ->\n Decode.fail <| ("Unknown type" ++ str)\n )\n\n\ndecodeSection : Decoder Section\ndecodeSection =\n Decode.map2 Section\n (Decode.field "type" decodeType)\n (Decode.field "index" Decode.int)\nRun Code Online (Sandbox Code Playgroud)\n如果我解码 JSON
\n{\n "sections": [{type: "A", index: 1}, {type: "invalid-type", index: 2}]\n}\nRun Code Online (Sandbox Code Playgroud)\n我期望我的部分 = [ {type = A, index= 1} ]
\n一般来说,处理这些问题的方法是将其解码为表示选项的 Elm 类型,然后使用map.
例如,在你的例子中,我会选择这样的东西:
decodeMaybeType : Decoder (Maybe Type)
decodeMaybeType =
Decode.string
|> Decode.map getTypeFromString
decodeMaybeSection : Decoder (Maybe Section)
decodeMaybeSection =
Decode.map2 (\maybeType index -> Maybe.map (\t -> Section t index) maybeType)
(Decode.field "type" decodeMaybeType)
(Decode.field "index" Decode.int)
decodeSections : Decoder (List Section)
decodeSections =
Decode.list decodeMaybeSection
|> Decode.map (List.filterMap identity)
Run Code Online (Sandbox Code Playgroud)
注意:List.filterMap identity是 a ,它会一次性List (Maybe a) -> List a过滤掉Nothing并摆脱s 。Maybe