LoginSignup
0
0

More than 5 years have passed since last update.

Elm でネストされたJSONを処理する

Last updated at Posted at 2018-01-21

Elm で API を呼び出して、ネストしている JSON を処理する時に少し迷ったのでここに書いておく。

以下のような Record を処理する。

type alias Item =
    { id : String
    , value : String
    }

必要なパッケージを Import

import Json.Decode as Decode
import Http

Msg を定義

以下の形式で呼び出される。

type Msg
    = ...
    | Init (Result Http.Error (List Item))

APIを呼び出す処理を定義

Cmdと、Http.Requestを定義する。

fetchItem : Cmd Msg
fetchItem =
    Http.send Init getItems

getItems : Http.Request (List Item)
getItems =
    Http.get "http://localhost:8080/items" decodeItems

JSONのパースする処理を定義

Itemをパースする処理を定義する。
Decode.mapXのXは、要素の数を指定する。

decodeItem : Decode.Decoder DateItem
decodeItem =
    Decode.map2 Item
        (Decode.field "id" Decode.string)
        (Decode.field "value" Decode.bool)

ItemのListをパースする処理を定義する。

decodeItems : Decode.Decoder (List Item)
decodeItems =
    Decode.list decodeItem

これを Http.get の引数に渡してあげるとネストした JSON が処理できる。

0
0
1

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