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}"
7 Likes

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