簡體   English   中英

解碼嵌套的JSON結構

[英]Decoding nested JSON structures

我正在嘗試使用elmplayground的源代碼,並且正在嘗試為博客創建配置json文件。 我現在遇到的問題是,我不知道如何將帖子/頁面作者解碼為嵌套結構。 我想要的是帖子和頁面中的author字段在config.json引用了一個作者。

config.json:

{
  "posts": [{
    "slug": "/hello-world",
    "title": "Hello World",
    "name": "hello-world",
    "publishedDate": "2016-10-30",
    "author": "Gabriel",
    "intro": ""
  }],
  "pages": [{
    "slug": "/hello",
    "name": "index",
    "title": "Elm Playground",
    "publishedDate": "2016-09-01",
    "author": "Gabriel",
    "intro": ""
  }],
  "authors": {
    "Gabriel": {
      "name": "Gabriel Perales",
      "avatar": "..."
    }
  }
}

鍵入頁面和帖子的內容:

type alias Content =
    { title : String
    , name : String
    , slug : String
    , publishedDate : Date
    , author : Author
    , markdown : WebData String
    , contentType : ContentType
    , intro : String
    }

類型作者:

type alias Author =
    { name : String
    , avatar : String
    }

當前,這是我的配置解碼器:

configDecoder : Decoder Config
configDecoder =
    Decode.map2 Config
        (field "posts" <| Decode.list <| decodeContent Post)
        (field "pages" <| Decode.list <| decodeContent Page)

decodeContent : ContentType -> Decoder Content
decodeContent contentType =
    Decode.map8 Content
        (field "slug" string)
        (field "name" string)
        (field "title" string)
        (field "publishedDate" decodeDate)
        (field "author"
            (string
                -- I want to decode the author from "authors"
                -- I have tried with 
                -- (\name -> at ["authors", name] decodeCofigAuthor) but it doesn\'t work
                |> andThen (\name -> Decode.succeed <| Author name "...")
            )
        )
        (Decode.succeed RemoteData.NotAsked)
        (Decode.succeed contentType)
        (field "intro" string)


decodeConfigAuthor : Decoder Author
decodeConfigAuthor =
    Decode.map2 Author
        (field "name" string)
        (field "avatar" string)

我將從解碼作者開始,然后使用andThen將作者Dict傳遞給decodeContent 然后,您可以使用Decode.map將作者姓名轉換為authors Dict的查找內容。

decoder =
    (field "authors" <| Decode.dict <| authorDecoder)
        |> Decode.andThen configDecoder

configDecoder authors =
    Decode.map2 Config
        (field "posts" <| Decode.list <| decodeContent Post authors)
        (field "pages" <| Decode.list <| decodeContent Page authors)

decodeContent contentType authors =
    Decode.map8 Content
        -- …
        (field "author" (string |> Decode.map (\name -> Dict.get name authors)))
        -- …

這會改變你的模型使用Maybe Author ,但你也可以使用Decode.andThen並返回Decode.fail如果Dict.get返回Nothing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM