1

In our project we use standard json encoders to encode our elm data models to json. As a result, I want to get a string that would look like a list of objects [{..}, {..}], but I get a rather unexpected result: an object where the keys are the index of the elements, and the values are the objects that I want to encode, that look like:

{
    "0": {"a":"b"}, 
    "1": {"c":"d"}
}

How I can override my encoders in order to get the desired list of objects? Our json encoders:

memberListEncoder : List Member -> Encode.Value
memberListEncoder memberList =
    Encode.list (List.map encodeMember memberList)

and

encodeMember : Member -> Encode.Value
encodeMember member =
    Encode.object
        [ ( "firstName", Encode.string member.firstName.value )
        , ( "lastName", Encode.string member.lastName.value )
        ]
glennsl
  • 28,186
  • 12
  • 57
  • 75
  • Can you include your definition for the `Member` type? – Chad Gilbert Oct 02 '18 at 13:42
  • This seems like a question specific to Elm 0.18, so I added a tag for that. Please correct me if I'm wrong though. – glennsl Oct 02 '18 at 13:53
  • I'm unable to reproduce the problem in Ellie (which uses 0.19). Could you provide a reproducible example including the definition of `Member`, the specific input value and how you convert the resulting `Encode.Value` to a string? – glennsl Oct 02 '18 at 13:58
  • Also, this looks a bit like how Firefox represents arrays of objects in the developer console. How do you observe the output? – glennsl Oct 02 '18 at 14:02

1 Answers1

1

Assuming Elm 0.19

While I have not yet seen your Member definition, I think the problem is that you do not need to use List.map in your memberListEncoder. The following should suffice:

memberListEncoder : List Member -> Encode.Value
memberListEncoder memberList =
    Encode.list encodeMember memberList
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • You answer applies to Elm 0.19, but I think this is 0.18 where you do need to use `List.map`: https://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode#list – glennsl Oct 02 '18 at 13:52