Json.Decode debug helpers

Hi. I would like to share helper functions which may be useful when one does JSON decoding debugging.


β€’ First helper function just logs decoded value to the console if the decoding was successful.

log : String -> Decode.Decoder a -> Decode.Decoder a
log message =
    Decode.map (Debug.log message)

Usage

import Json.Decode as Decode
import Extra.Json.Decode as Decode

type Point =
    Point Int Int

pointDecoder : Decode.Decoder Point
pointDecoder =
    Decode.map2 Point
        (Decode.log β€œX:” (Decode.field β€œx” Decode.int)) β€” Will log β€œX: 1”
        (Decode.field β€œy” Decode.int)
        |> Decode.log β€œPoint:” β€” Will log β€œPoint: Point 1 2”

point : Result Decode.Error Point
point =
    Decode.decodeString jsonDecoder "{ \"x\": 1, \"y\": 2}"

β€’ Second helper function logs the result of the decoding whether it was success or failure.

debug : String -> Decode.Decoder a -> Decode.Decoder a
debug message decoder =
    Decode.value
        |> Decode.andThen (debugHelper message decoder)


debugHelper : String -> Decode.Decoder a -> Decode.Value -> Decode.Decoder a
debugHelper message decoder value =
    let
        _ =
            Debug.log message (Decode.decodeValue decoder value)
    in
    decoder

Usage

import Json.Decode as Decode
import Extra.Json.Decode as Decode

type Point =
    Point Int Int

pointDecoder : Decode.Decoder Point
pointDecoder =
    Decode.map2 Point
        (Decode.debug β€œX:” (Decode.field β€œx” Decode.int)) β€” Will log β€œX: Ok 1”
        (Decode.field β€œy” Decode.int)
        |> Decode.debug β€œPoint:” β€” Will log β€œPoint: Ok (Point 1 2)”

point : Result Decode.Error Point
point =
    Decode.decodeString jsonDecoder "{ \"x\": 1, \"y\": 2}"
11 Likes

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