ELM解析嵌套的json

Bou*_*TAC 6 parsing json decode reddit elm

我有一个带有多个注释的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": ""
  },
]
Run Code Online (Sandbox Code Playgroud)

所以这是一个评论列表,每个评论都可以回复无限回复.随着Json.Decode.list我可以解码注释的第一个层次,但我要如何检查是否有一些答复,然后再解析?

这是我尝试做的简化版本.我实际上是在尝试解码reddit评论.为例

Cha*_*ert 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": ""
  }]
}]
"""
Run Code Online (Sandbox Code Playgroud)

(你的json在其他方面也略有不同:在列表的最后部分之后还有一些额外的逗号,其中一个reply字段丢失了)