Better way for type models

I am starting my very first try on elm. Will get json data from server like below:

{

“categories” : {

"Featured" : [ ],

"New" : [ ],

"Recommend" : [ {

  "productId" : "Product-1",
  ...
  ...

}, {

  "productId" : "Product-2",

  ...
  ...

} ],

"Slides" : [ {

  "productId" : "Product-3",

  ...
  ...

}, {

  "productId" : "Product-4",

  ...
  ...

} ]

}

}

I am modeling like below:

type alias Product =
{ productId : String


}

type alias Categories =
{ Featured: List Product
, New: List Product
, Recommend: List Product
, Slides: List Product
}

type alias Model =
{ categories : WebData (Categories)
}

This will not work, as Elm need lower case name, Featured, New… will not get through.

So in my case, how to model the categories?

The field names do not have to be (and in this case cannot be) the same as your source data. Your data model could even have a different structure, though it is often easier to keep them similar. You specify the field names in your Json decoders. Decoders can be a little tricky to understand at first, so I made a quick example for the sample you showed.

https://ellie-app.com/qRpQhZwxw7a1

I normally do the import Json.Decode exposing(..) in a dedicated deserialization module where there is much less risk to importing all symbols.

2 Likes

Thank you, this is quite helpful

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.