榆树:如何使用Json

时间:2015-12-04 16:11:42

标签: json elm

我不知道如何使用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 ]

我希望得到&#34; a&#34;。

的价值

我不知道&#34;好的{a = 2,b = 2}&#34;。

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

1 个答案:

答案 0 :(得分:1)

由于decodeString返回Result String a,因此可能是错误或成功结果。你必须做一个案例陈述并寻找OkErr,如下所示:

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 ]