I'm new to Elm (I'm <2 weeks in) but am really loving it.
However, I'm finding it difficult to determine just how to successfully
decode a JSON object into my model, what with changes between versions, and
the number of related non-core packages.
Here's an example of the JSON data:
[
{
"id" : 1,
"day" : "today",
"time" : 12,
"product" : "ProductType",
"location" : "locationOne",
"quantity" : 25,
"status" : "Draft"
},
{
"id" : 2,
"day" : "tomorrow",
"time" : 15,
"product" : "ProductType",
"location" : "locationTwo",
"quantity" : 15,
"status" : "Cancelled"
},
...
]
...and here are my Elm type descriptions:
type OrderStatus
= Draft
| Ordered
| Inbound
| Delivered
| Cancelled
type alias Order =
{ id : Int
, day : String
, time : Int
, product : Product
, location : String
, quantity : Int
, status : OrderStatus
}
Focussing specifically on Order and OrderStatus, I've got something along
the lines of this, so far:
orderListDecoder : Decoder (List Order)
orderListDecoder =
list orderDecoder
orderDecoder : Decoder Order
orderDecoder =
map7 Order
("id" field int)
("day" field string)
("time" field int)
("product" field productDecode)
("location" field string)
("quantity" field int)
("status" field orderStatusDecoder)
orderStatusDecoder : Decoder OrderStatus
orderStatusDecoder =
string |> andThen fromStringOrderStatus
fromStringOrderStatus : String -> Result String OrderStatus
fromStringOrderStatus string =
case string of
"Draft" ->
Ok Draft
"Ordered" ->
Ok Ordered
"Inbound" ->
Ok Inbound
"Delivered" ->
Ok Delivered
"Cancelled" ->
Ok Cancelled
other ->
Err ("Invalid OrderStatus: " ++ string)
So specifically, I can't figure out how to decode the 'status' JSON string
into an OrderStatus type.
I'm sure there's a simple solution, but I'm getting confused with the many
pre-0.18 examples of decoding, and the various extra packages available.
--
You received this message because you are subscribed to the Google Groups "Elm
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.