gpt4 book ai didi

json - 如何解码具有剩余值的异构数组作为列表

转载 作者:行者123 更新时间:2023-12-05 01:17:24 25 4
gpt4 key购买 nike

我想像下面这样解码 json 字符串。

"[[\"aaa\",1,2,3,4],[\"bbb\",1,2,3]]"

并解码为 Elm 元组列表。

[("aaa",[1,2,3,4]),("bbb",[1,2,3])] : List (String, List Int)

如何解码?

jsdecode=index 0 string
|> andThen xxxxxxx??

最佳答案

这不是一件容易的事,但在我直接跳到如何去做之前,让我收集一系列关于我们试图解码的数据的想法:

  • 我们正在解码列表列表
  • 每个列表应该由一个起始字符串和一系列值组成
  • 但实际上可能有一个空列表,没有初始字符串但有一些值或初始字符串没有值

因此在我看来,构建正确解码器的难度反射(reflect)了处理所有这些边缘情况的复杂性。但是让我们开始定义我们想要的数据:

type alias Record =
( String, List Int )


type alias Model =
List Record

jsonString : String
jsonString =
"[[\"aaa\",1,2,3,4],[\"bbb\",1,2,3]]"

decoder : Decoder Model
decoder =
Decode.list recordDecoder

现在我们需要定义一个类型来表示列表可以包含字符串或整数

type EntryFlags
= EntryId String
| EntryValue Int


type RecordFlags
= List EntryFlags

现在是我们的解码器

recordDecoder : Decoder Record
recordDecoder =
Decode.list
(Decode.oneOf
[ Decode.map EntryId Decode.string
, Decode.map EntryValue Decode.int
]
)
|> Decode.andThen buildRecord

所以 buildRecord 获取这个 EntryId StringEntryValue Int 的列表并构建我们正在寻找的记录。

buildRecord : List EntryFlags -> Decoder Record
buildRecord list =
case list of
[] ->
Decode.fail "No values were passed"

[ x ] ->
Decode.fail "Only key passed, but no values"

x :: xs ->
case buildRecordFromFlags x xs of
Nothing ->
Decode.fail "Could not build record"

Just value ->
Decode.succeed value

如您所见,我们在解码器中处理了很多边缘情况。现在,让我们检查一下 buildRecordFromFlags 的最后一点:

buildRecordFromFlags : EntryFlags -> List EntryFlags -> Maybe Record
buildRecordFromFlags idEntry valueEntries =
let
maybeId =
case idEntry of
EntryId value ->
Just value

_ ->
Nothing

maybeEntries =
List.map
(\valueEntry ->
case valueEntry of
EntryValue value ->
Just value

_ ->
Nothing
)
valueEntries
|> Maybe.Extra.combine
in
case ( maybeId, maybeEntries ) of
( Just id, Just entries ) ->
Just ( id, entries )

_ ->
Nothing

在最后一点,我们使用了来自 maybe-extra 的函数验证初始 EntryId 之后的所有值确实都是 EntryValue 类型。

您可以在此处查看工作示例:https://ellie-app.com/3SwvFPjmKYFa1

关于json - 如何解码具有剩余值的异构数组作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53276026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com