我有一个带有多个注释的json数组,可以嵌套。
为例:
[
{
"author": "john",
"comment" : ".....",
"reply": "",
},
{
"author": "Paul",
"comment" : ".....",
"reply": [
{
"author": "john",
"comment" : "nested comment",
"reply": [
{
"author": "Paul",
"comment": "second nested comment"
}
]
},
{
"author": "john",
"comment" : "another nested comment",
"reply": ""
}
]
},
{
"author": "Dave",
"comment" : ".....",
"reply": ""
},
]
所以它是一个评论列表,每个评论都可以回复无限回复。
使用Json.Decode.list
我可以解码第一级评论,但如何检查是否有回复然后再次解析?
这是我尝试做的简化版本。我实际上试图解码reddit评论。 exemple
答案 0 :(得分:6)
Elm不允许您创建递归记录类型别名,因此您必须使用Customer
的联合类型。您可能还需要一个便利功能来创建用户,以便您可以使用Json.map3
。
您的示例json有一个奇怪之处:有时reply
是一个空字符串,有时候它是一个列表。您需要一个特殊的解码器将该字符串转换为空列表(假设空列表与此上下文中的空列表同义)。
由于您具有递归类型,因此需要使用lazy
来解码子注释以避免运行时错误。
import Html exposing (Html, text)
import Json.Decode as Json exposing (..)
main : Html msg
main =
text <| toString <| decodeString (list commentDecoder) s
type Comment
= Comment
{ author : String
, comment : String
, reply : List Comment
}
newComment : String -> String -> List Comment -> Comment
newComment author comment reply =
Comment
{ author = author
, comment = comment
, reply = reply
}
emptyStringToListDecoder : Decoder (List a)
emptyStringToListDecoder =
string
|> andThen
(\s ->
case s of
"" ->
succeed []
_ ->
fail "Expected an empty string"
)
commentDecoder : Decoder Comment
commentDecoder =
map3 newComment
(field "author" string)
(field "comment" string)
(field "reply" <|
oneOf
[ emptyStringToListDecoder
, list (lazy (\_ -> commentDecoder))
]
)
s =
"""
[{
"author": "john",
"comment": ".....",
"reply": ""
}, {
"author": "Dave",
"comment": ".....",
"reply": ""
}, {
"author": "Paul",
"comment": ".....",
"reply": [{
"author": "john",
"comment": "nested comment",
"reply": [{
"author": "Paul",
"comment": "second nested comment",
"reply": ""
}]
}, {
"author": "john",
"comment": "another nested comment",
"reply": ""
}]
}]
"""
(你的json在其他方面也有点偏差:在列表的最后部分之后还有一些额外的逗号,其中一个reply
字段丢失了)