Quick example how to use Encoder and Decoder with a nested

import Json.Decode as Decode exposing (Decoder, int, float, list, string)

import Json.Decode.Pipeline exposing (required, optional)

import Json.Encode as Encode                        

-- ###################################################

-- NOTE: Model

-- ###################################################

type alias Test =

    { id : String

    , name : String

    , instructions : String

    , sections : List Section

    }

type alias Section =

    { name : String

    , questions : List Question

    }

type alias Question =

    { question : String

    , variable : String

    }

emptyTest : Test

emptyTest = 

    { id = ""

    , name = ""

    , instructions = ""

    , sections = []

    }


questionDecode : Decoder Question

questionDecode = 

    Decode.succeed Question

        |> required "question" string 

        |> required "variable" string

sectionDecoder : Decoder Section

sectionDecoder = 

    Decode.succeed Section

        |> required "name" string 

        |> required "questions" (list questionDecode)

testDecoder : Decoder Test

testDecoder =

    Decode.succeed Test

        |> optional "id" string ""

        |> required "name" string

        |> required "instructions" string

        |> required "sections" (list sectionDecoder)



questionEncoder : Question -> Encode.Value

questionEncoder question = 

    Encode.object

        [ ( "question", Encode.string question.question )

        , ( "variable", Encode.string question.variable )

        ]

sectionEncoder : Section -> Encode.Value

sectionEncoder section =

    Encode.object

        [ ( "name", Encode.string section.name )

        , ( "questions", Encode.list questionEncoder section.questions)

        ]

newTestEncoder : Test -> Encode.Value

newTestEncoder test =

    Encode.object

        [ ( "name", Encode.string test.name )

        , ( "instructions", Encode.string test.instructions )

        , ( "sections", Encode.list sectionEncoder test.sections )

        ]

I don’t understand what you are trying to communicate

I saw this post How to encode/decode nested entities? but is not complete and I wanted to show a complete example of how to use correctly a nested model with Decode and Encode

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.