Sandeep Chayapathi
Sandeep Chayapathi

Reputation: 1610

Decode and flatten nested json into an Elm record

I just started learning Elm and I have hit a roadblock. Looking for some help from this awesome community.

I'm looking to decode a nested json and pulling in a particular nested value into a elm record.

The json source looks like this:

 {
    "id": 672761,
    "modified": "2018-02-12T00:53:04",
    "slug": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.",
    "type": "post",
    "link": "https://awesomelinkhere.com",
    "title": {
        "rendered": "Sed posuere consectetur est at lobortis."
    },
    "content": {
        "rendered": "Nulla vitae elit libero, a pharetra augue.",
    },
    "excerpt": {
        "rendered": "Donec sed odio dui.",
    }
}

and I want to pull apart the title.rendered and content.rendered into a field in my model , the model looks like so:

type alias Post =
    { id : Int
    , published : String
    , title : String
    , link : String
    , slug : String
    , excerpt : String
    }

my naive decoder looks like this

postDecoder : Decoder Post
postDecoder =
    Decode.map6 Post
        (field "id" Decode.int)
        (field "modified" Decode.string)
        (field "title" Decode.string)
        (field "link" Decode.string)
        (field "slug" Decode.string)
        (field "excerpt" Decode.string)

Upvotes: 7

Views: 495

Answers (1)

Sandeep Chayapathi
Sandeep Chayapathi

Reputation: 1610

Update

As it usually happens I found the answer as soon as I posted this. I reviewed the Json.Decode documentation and stumbled on the at function

my working decoder looks like this now

postDecoder : Decoder Post
postDecoder =
    Decode.map6 Post
        (field "id" Decode.int)
        (field "modified" Decode.string)
        (at [ "title", "rendered" ] Decode.string)
        (field "link" Decode.string)
        (field "slug" Decode.string)
        (at [ "excerpt", "rendered" ] Decode.string)

Upvotes: 7

Related Questions