- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想像下面这样解码 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 String
或 EntryValue 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/
我有一个 NSTreeController (向 NSOutlineView 提供内容)。我希望顶级对象属于一个类,而所有其他对象(因此,任何级别的子对象)属于另一个类。解决这个问题的最佳方法是什么?
我有一个如下所示的 GADT data MyTypes = MyInt | MyDouble data Test (t :: MyTypes) where A :: Int -
我需要一个高效的异构数组,其中第一个元素是 int,其余是 float。然而,创建它之后,基本的数组操作就会呈爆炸式增长。 A = np.zeros(1, dtype='i4, f4, f4') B
我有一个 pandas DataFrame,其中包含需要拆分成平衡切片的字符串和浮点列,以便训练 sklearn 管道。 理想情况下,我会使用 StratifiedKFold在 DataFrame 上
是否有一种异构容器的形式,能够存储例如不同的基本类型(例如int、float、double)? 最终我希望能够在计算中使用元素而无需显式引用类型,例如 auto res = a + b,其中操作数 a
假设我有一个结构(或类),如下所示: struct _particle { std::vector vx , vy; std::vector id; std::vector rx, ry; }; ty
我在将具有 > 22 列的表专门映射到 case class 时遇到问题,假设您有以下代码 import slick.driver.PostgresDriver import scala.slick.
我是一名优秀的程序员,十分优秀!