I want to parse a JSON like this:
{ "shapes":[
{
"shape": "circle",
"x": "50",
"y": "50",
"r": "40"
},
{
"shape": "rect",
"x": "100",
"y": "100",
"width": "50",
"height": "60"
},
]}
and this is my Elm code:
type alias Model =
{ input : Shape
, saved : List Shape
, modal1 : String
, modal2 : String
, modal3 : String
, region : String
}
type Shape
= Circle String String String
| Rectangle String String String String
type Msg
= LoadJson
| JsonLoaded (Result Http.Error (List Shape))
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
LoadJson ->
(model, getJson)
JsonLoaded (Ok shapes) ->
({ model | saved = shapes }, Cmd.none)
JsonLoaded (Err _) ->
(model, Cmd.none)
getJson =
let
url =
"http://www.mywebsite.de/shapes.json"
in
Http.send JsonLoaded (Http.get url decoder)
decoder =
at ["shapes"] (list shapeDecoder)
shapeDecoder =
decode func
|> required "shape" string
|> required "x" string
|> required "y" string
|> optional "r" string ""
|> optional "width" string ""
|> optional "height" string ""
func shape x y r width height =
case shape of
"circle" ->
Circle x y r
"rect" ->
Rectangle x y width height
"polygon" ->
Circle "" "" ""
_ ->
Circle "" "" ""
All shapes in the list which is called "saved" are supposed to be listed in a table.
If I write some elements in this list, they are shown in the table but not if I'm trying to get them from my JSON. Something has to be wrong with my decoder but I don't know what.
Thank you for your help.
Aucun commentaire:
Enregistrer un commentaire