Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode and flatten nested json into an Elm record

Tags:

elm

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)
like image 325
Sandeep Chayapathi Avatar asked Feb 12 '18 04:02

Sandeep Chayapathi


1 Answers

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)
like image 148
Sandeep Chayapathi Avatar answered Nov 15 '22 09:11

Sandeep Chayapathi