【问题标题】:Access field of type after Json decode in elmelm中Json解码后的访问类型字段
【发布时间】:2019-07-29 15:37:23
【问题描述】:

我正在尝试使用 elm 宽度将 json 解码为类型来做一些小步骤。我的类型是例如:

    type alias Project = 
        { title : String
        , description : String
        }

和我的函数一起解码逻辑并显示项目的标题。

    render : (String, String) -> Html Msg
    render (jsonString, otherString) =
        let project = Decode.decodeString projectDecoder (jsonString)
        in div [] [ text (project.title) ]
projectDecoder : Decode.Decoder Project
projectDecoder =
    Decode.map2
        Project
        (Decode.at [ "title" ] Decode.string)
        (Decode.at [ "description" ] Decode.string)

但是我有一个错误,表明解码器将返回一个错误而不是一个项目。

这不是一条记录,所以它没有可访问的字段!

32|在 div [] [ 文本 (project.title) ] 这个project 值是:

Result Decode.Error Project

但我需要一个带有标题字段的记录!

【问题讨论】:

    标签: json elm


    【解决方案1】:

    仔细阅读榆树指南将有助于解决这个问题:https://guide.elm-lang.org/error_handling/result.html

    我们需要用case 处理OkErr 这两种情况。

    render : (String, String) -> Html Msg
    render (jsonString, otherString) =
        let project = Decode.decodeString projectDecoder (jsonString)
        in 
            case project of
                Ok status -> div [] [ text (status.title) ]
                Err _ -> div [] [ text ("A error occurs") ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2021-11-23
      • 2017-03-04
      相关资源
      最近更新 更多