Track Successes and Failures

To track successes and failures when using Decode.oneOf, you can use Result type to capture the outcome of each decoding attempt.

Instead of directly applying Decode.oneOf to a list of decoders, you can map each decoder with Decode.attempt to wrap it in a Result type. This way, you can keep track of the success or failure of each decoding attempt.

Json.Decode.Attempt, a package to fail loudly and gracefully discourse , page , github

Here's an example: (ChatGPT May 24 Version)

import Json.Decode exposing (Decode) import Result exposing (Result(..)) -- Define decoders decoder1 : Decode Int decoder1 = Decode.int decoder2 : Decode String decoder2 = Decode.string decoder3 : Decode Bool decoder3 = Decode.bool -- Wrap decoders with Decode.attempt to capture successes and failures attemptedDecoder1 : Decode (Result String Int) attemptedDecoder1 = Decode.attempt (\value -> Ok value) decoder1 attemptedDecoder2 : Decode (Result String String) attemptedDecoder2 = Decode.attempt (\value -> Ok value) decoder2 attemptedDecoder3 : Decode (Result String Bool) attemptedDecoder3 = Decode.attempt (\value -> Ok value) decoder3 -- Combine attempted decoders using Decode.oneOf combinedDecoder : Decode (Result String (Int, String, Bool)) combinedDecoder = Decode.oneOf [ Decode.map (\value -> (value, "", False)) attemptedDecoder1 , Decode.map (\value -> (0, value, False)) attemptedDecoder2 , Decode.map (\value -> (0, "", value)) attemptedDecoder3 ] -- Example usage json1 : String json1 = "42" json2 : String json2 = "\"Hello, World!\"" json3 : String json3 = "true" result1 : Result String (Int, String, Bool) result1 = Decode.decodeString combinedDecoder json1 result2 : Result String (Int, String, Bool) result2 = Decode.decodeString combinedDecoder json2 result3 : Result String (Int, String, Bool) result3 = Decode.decodeString combinedDecoder json3

In the example above, attemptedDecoder1, attemptedDecoder2, and attemptedDecoder3 are the individual decoders wrapped with Decode.attempt to capture their successes as Ok results. If a decoder fails, the Err result will be captured. Then, these attempted decoders are combined using Decode.oneOf to create a single decoder, combinedDecoder, which returns a tuple of the decoded values along with their success or failure status.

By using the Result type, you can inspect the outcome of each decoding attempt and handle successes and failures accordingly. This allows you to track and handle different decoding scenarios in a controlled manner.