对象通过 Elm 端口进入 JSON 解码器
Objects into JSON decoder through Elm ports
我正在通过端口将一组对象传递到我的 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 代码中做到这一点。
Json.Decode.decodeValue
可以解码一个Json.Decode.Value
,但是returns一个Result String (List Person)
.
如果您这样定义 Msg:
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
)
我正在通过端口将一组对象传递到我的 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 代码中做到这一点。
Json.Decode.decodeValue
可以解码一个Json.Decode.Value
,但是returns一个Result String (List Person)
.
如果您这样定义 Msg:
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
)