How to JSON.Encode multiple levels


#1

I am upgrading from 18 to 19.

I am trying to refactor my code that previously produced a list of objects, but am getting errors with the new JSON.Encode API that I don’t know how to solve.

My previous (working) code was the same as that listed below, without the object parameter on line 54.

-- TYPE MISMATCH -------------------------------------------- src/Chart/View.elm

The 2nd argument to `list` is not what I expect:

54|           , list object
55|>                [ object
56|>                    [ ( "v", string (date2String record.date) )
57|>                    ]
58|>                , object [ ( "v", string (tooltip record.date record.current chartDataType currency) ) ]
59|>                , object
60|>                    [ ( "v", rawValue record.current chartDataType )
61|>                    , ( "f", string (formatValue record.current chartDataType currency) )
62|>                    ]
63|>                , object [ ( "v", string (getBarColor record.date) ) ]
64|>                ]

This argument is a list of type:

    List Value

But `list` needs the 2nd argument to be:

    List (List ( String.String, Value ))

Hint: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is “correct” and move on. So the problem may actually
be in one of the previous arguments!
Detected errors in 1 module.

#2

Hi,

The type of Json.Encode.list is similar to the type of List.map, the first argument is a function which encodes each value. You already have a list of encoded values so you could just provide identity as the first argument to your Json.Encode.list call. Alternatively if all the values you wish to encode are “objects”, you could just remove the object call from the start of all of your list elements.

I’m not sure of the exact JSON that you’re hoping to produce, you have a couple of “objects” that are only one field. So I don’t know if you’re just using this as a minimal example or that really is the JSON you want to produce, or you’d rather produce those as direct fields.