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 )