0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Elm] HttpリクエストからのDecodeしてみる

Last updated at Posted at 2019-11-21

概要

elmでhttpリクエストして帰ってくるJsonをDecodeしようと思います。
使うapiはgithubAPIです。
https://api.github.com/users/この後にユーザー名を入れることで以下のJsonが帰ってきます。

https://api.github.com/users/kuropp の場合
image.png

それではやっていきましょう。
必要なモジュールをインストールしてください。

elm install elm/http
elm install elm/json

Decode

import Json.Decode as D exposing (Decoder)

type Msg
    = Click
    | Receive (Result Http.Error User)

update msg model =
    case msg of 
        Click ->
            ( -- modelの書き換え処理
            , Http.get
                  { url = "https://api.github.com/users/" ++ model.input)
                  , expect = Http.expectJson Receive userDecoder
                  }
            )

        -- Receive (OK user)の処理
        -- Receive (Err e)の処理

type alias User = 
    { login : Stirng
    , avatarUrl : String
    , htmlUrl : String
    }

userDecoder : Decorder User
userDecoder = 
    D.map3 User
        (D.field "login" D.string)
        (D.field "avatar_url" D.string)
        (D.field "html_url" D.string)

field関数により帰ってくるJsonから第一引数の値を見つけ、stringによりDecodeしています。

まとめ

elmのdecodeを学んだので復習として記しました。
全体的なコードはgithubにあげています。
参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?