Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Decode.Pipeline on a list (elm 0.18)

Tags:

json

decode

elm

I have a type alias with a nested list that I want to parse with Json.Decode.Pipeline.

import Json.Decode as Decode exposing (..)
import Json.Encode as Encode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

type alias Student =
    { name : String
    , age : Int
    }

type alias CollegeClass =
    { courseId : Int
    , title : String
    , teacher : String
    , students : List Student
    }

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> -- what goes here?

How does this work?

like image 517
Mark Karavan Avatar asked Sep 17 '17 03:09

Mark Karavan


People also ask

What decoders does Elm support for JSON?

Elm provides three other decoders for translating primitive JSON types to Elm values: int, float, and bool. Here are some examples showing them in action: JSON supports the following data types:

What decoders are available for primitive JSON types?

Elm provides three other decoders for translating primitive JSON types to Elm values: int, float, and bool. Here are some examples showing them in action:

What is the difference between JSON and string in Elm?

For JSON, the server uses application/json as the Content-Type header’s value. Whereas, for string it uses text/plain. Elm provides a package called elm/json which includes modules for encoding and decoding JSON values.

How does the decodestring function work in Elm?

The decodeString function is the one that does the actual decoding. It first parses the raw string into JSON and then applies the string decoder to translate that JSON into an Elm string. The following diagram explains the type signature of decodeString in detail. When decoding fails, decodeString returns a value of type Error.


1 Answers

You'll need to pass a decoder to Decode.list. In your case, it'll be a custom one based on the shape of your Student type.

This hasn't been tested, but something like the following should work:

studentDecoder =
    decode Student
        |> required "name" Decode.string
        |> required "age" Decode.int

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> Pipeline.required "students" (Decode.list studentDecoder)

See this post on writing custom flag decoders which should be instructive.

like image 58
pdoherty926 Avatar answered Sep 24 '22 21:09

pdoherty926