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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With