# Json.Decode debug helpers

**URL:** <https://discourse.elm-lang.org/t/json-decode-debug-helpers/3868>\
**Category:** Show and Tell\
**Created:** [June 24, 2019, 2:31pm UTC](https://discourse.elm-lang.org/t/json-decode-debug-helpers/3868 "2019-06-24T14:31:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![akoppela](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/akoppela/32/250_2.png) [@akoppela](https://discourse.elm-lang.org/u/akoppela)\
**Post date:** [June 24, 2019, 2:31pm UTC](https://discourse.elm-lang.org/t/json-decode-debug-helpers/3868/1 "2019-06-24T14:31:02Z")

</div>

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.

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

```

Usage

```elm
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.

```auto
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

```elm
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}"

```

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex035/uploads/elm_lang/original/1X/50a05e53677a2c3b47776d7abd0f113eb50193a1.png) [@system](https://discourse.elm-lang.org/u/system)\
**Post date:** [July 4, 2019, 2:31pm UTC](https://discourse.elm-lang.org/t/json-decode-debug-helpers/3868/2 "2019-07-04T14:31:07Z")

</div>

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