Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
1

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でWebAPIから受け取ったオブジェクト配列のレスポンスをRecordにマッピングする

Posted at

たとえば以下のような JSON が WebAPI からレスポンスとして返ってくることを想定する

[
  {
    "name": "juestine",
    "age": 21
  },
  {
    "name": "alice",
    "age": 23
  }
]

このレスポンスを以下の Person レコードにマッピングするにはこのような実装にする。
fetchPeople を呼ぶと WebAPI へのフェッチが走る。

import Json.Decode as Decode exposing (field, string, int)

-- 省略...

type Msg =
  | PeopleFetched (Result Http.Error (List Person))

-- 省略...

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

fetchPeople : Cmd Msg
fetchPeople =
  Http.get {
    url = "http://your-own-web-api/users",
    expect = Http.expectJson PeopleFetched peopleFetchingDecoder
  }

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

peopleFetchingDecoder : Decode.Decoder (List Person)
peopleFetchingDecoder =
  Decode.list personDecoder

あとは PeopleFetched で受け取れる Result 型のメッセージを煮るなり焼くなり好きにする。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?