通过 Elm 端口将对象转换为 JSON 解码器

jos*_*y10 3 elm

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

{
    FullName: 'Foo Bar',
    Location: 'Here'
}
Run Code Online (Sandbox Code Playgroud)

如您所见,对象中的键以大写开头,因此我需要在 Elm 中对它们进行解码。在我的榆树代码,我有一个typePerson

type alias Person =
    { fullName : String
    , location : String
    }
Run Code Online (Sandbox Code Playgroud)

和港口:

port getPeople : (List Json.Decode.Value -> msg) -> Sub msg
Run Code Online (Sandbox Code Playgroud)

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

peopleDecoder : Decoder Person
peopleDecoder =
    decode Person
        |> required "FullName" string
        |> required "Location" string
Run Code Online (Sandbox Code Playgroud)

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

Cha*_*ert 5

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

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

type Msg
    = GetPeople (Result String (List Person))
Run Code Online (Sandbox Code Playgroud)

您可以像这样设置订阅:

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

subscriptions : Model -> Sub Msg
subscriptions model =
    getPeople (GetPeople << decodeValue (list peopleDecoder))
Run Code Online (Sandbox Code Playgroud)

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