takata
takata

Reputation: 25

Elm: How to use Json

I do not know how to use Json.decode.

type alias Test =
    { a : Int
    , b : Int
    }

testDecoder =
    object2 Test
        ("a" := int)
        ("b" := int)

main : Html
main =
    let
        t = "{\"a\":2, \"b\":2}"
        d = decodeString testDecoder t
    in
        p [] [ text <| toString <| d ]

I want to get value of "a".

I do not know "Ok { a = 2, b = 2 }".

decodeString : Decoder a -> String -> Result String a

Upvotes: 1

Views: 306

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

Since decodeString returns a Result String a, it could either be an error or success result. You have to do a case statement and look for Ok and Err, like so:

main : Html
main =
    let
        t = "{\"a\":2, \"b\":2}"
        d = decodeString testDecoder t
        myText =
            case d of
                Ok x -> toString x.a
                Err msg -> msg
in
    p [] [ text myText ]

Upvotes: 1

Related Questions