You need to create a decoder that creates a record from the data at the parent level and attaches it to all child records in elms

I have json like this:

{
  "username": "john",
  "email": "john@gmail.com",
  "items": [
     { 
        "id": "id 1"
     },
     { 
        "id": "id 2" 
     }
  ]
}

I need to decode it in List Item. An item is a record like this.

type alias Item =
    { id : String
    , user : User
    }

type alias User =
    { username : String
    , email : String
    }

I want to extract username and email address from top level json. Then create an entry User, and then put that user in each entry Itemin List Item.

I understand that this can be done using Decode.andThen, but cannot make it work.

For decoding, I use json-decode-pipeline .

thank

+4
source share
1 answer

andThen. JSON ( json-decode-).

. :

userDecoder : Decoder User
userDecoder =
    map2 User
        (field "username" string)
        (field "email" string)

Item, , User, user. , :

itemDecoder : User -> Decoder Item
itemDecoder user =
    map2 Item
        (field "id" string)
        (succeed user)

. , itemDecoder :

itemsDecoder : Decoder (List Item)
itemsDecoder =
    userDecoder
        |> andThen (\user ->
            field "items" (list (itemDecoder user)))

:

itemsDecoder : Decoder (List Item)
itemsDecoder =
    userDecoder
        |> andThen (field "items" << list << itemDecoder)

ellie-app.com.

+5

Source: https://habr.com/ru/post/1671243/


All Articles