DEV Community

Discussion on: #30daysofelm Day 16: Struggling slightly less with JSON

Collapse
 
bukkfrig profile image
bukkfrig • Edited

Its full name is JSON.Decode.decodeString, and it's what you want for converting anything to a string, I guess. :)

No, it's for reading from a String into any Elm type.

Instead of getPersonInfo that has to know something about Decoder and do formatting, instead just decode your JSON into a Person and then have a regular viewPerson.

module Main exposing (main)

import Html exposing (..)
import Json.Decode exposing (..)


type alias Person =
    { name : String, age : Int }


viewPerson : Person -> Html msg
viewPerson { name, age } =
    pre []
        [ text ("Name: " ++ name)
        , br [] []
        , text ("Age: " ++ String.fromInt age)
        ]


personDecoder : Decoder Person
personDecoder =
    map2 Person
        (field "name" string)
        (field "age" int)


main : Html msg
main =
    case
        decodeString personDecoder
            """{ "name" : "Kristian", "age" : 31 }"""
    of
        Ok person ->
            viewPerson person

        Err err ->
            pre []
                [ text "Oops: "
                , br [] []
                , text ("    " ++ Debug.toString err)
                ]
Enter fullscreen mode Exit fullscreen mode

You can use Json.Decode.decodeString like this to test your Decoders. Once you're ready to bring back the API stuff, you probably won't have a need for it, and instead you'll just be passing those decoders directly to Http.expectJson.