【问题标题】:Objects into JSON decoder through Elm ports对象通过 Elm 端口进入 JSON 解码器
【发布时间】:2016-12-20 20:58:12
【问题描述】:

我通过端口将一组对象传递到我的 Elm 应用程序中。数组中的一个对象的示例是:

{
    FullName: 'Foo Bar',
    Location: 'Here'
}

您可以看到对象中的键以大写字母开头,因此我需要在 Elm 中对它们进行解码。在我的 Elm 代码中,我有一个 type 用于 Person

type alias Person =
    { fullName : String
    , location : String
    }

和港口:

port getPeople : (List Json.Decode.Value -> msg) -> Sub msg

最后我有一个解码器(我正在使用Elm Decode Pipeline)将数据解析为Person 类型。

peopleDecoder : Decoder Person
peopleDecoder =
    decode Person
        |> required "FullName" string
        |> required "Location" string

我的问题是如何将传入的端口数据映射到Person 类型?我知道我可以在 JS 中做到这一点,但我宁愿在我的 Elm 代码中做到这一点。

【问题讨论】:

  • 在您的示例中Worker 是什么peopleDecoder
  • 那是一个错字,现在更正了。

标签: elm


【解决方案1】:

Json.Decode.decodeValue 可以解码Json.Decode.Value,但它会返回Result String (List Person)

如果你这样定义你的消息:

type Msg
    = GetPeople (Result String (List Person))

您可以这样设置订阅:

port getPeople : (Json.Decode.Value -> msg) -> Sub msg

subscriptions : Model -> Sub Msg
subscriptions model =
    getPeople (GetPeople << decodeValue (list peopleDecoder))

(请注意,端口中的第一个参数已更改为 Value 而不是 List Value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2018-12-07
    • 2020-05-02
    • 2018-04-10
    • 2013-02-27
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多