Decode fails on empty string

368 views
Skip to first unread message

Richard Osafo

unread,
May 17, 2016, 4:45:54 AM5/17/16
to Elm Discuss
Hi,
I was decoding an http response (body can be blank) and realized that Decode fails on empty string. Gives the error "Given an invalid JSON: Syntax error". Is this by design or a bug?


import Html exposing (text)
import Json.Decode as Decode exposing (..)


main =
  text <| toString test


test =
  [ succeed "cool"
  , fail "oh"
  , null "what?"
  ]
  |> List.map (flip decodeString "")


If it is by design, what is the recommended way of decoding string that can be blank.

For now, I'm using

    let
      x' =
        if x == "" then "\"\"" else x
    in
      case decodeString decoder x' of
        ...



regards,
Richard.

Janis Voigtländer

unread,
May 17, 2016, 4:52:24 AM5/17/16
to elm-d...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Fedor Nezhivoi

unread,
May 17, 2016, 4:54:08 AM5/17/16
to elm-d...@googlegroups.com
Empty string isn't valid JSON. Try open Chrome DevTools and write JSON.parse("").
--
Best regards,
Fedor Nezhivoi.

Janis Voigtländer

unread,
May 17, 2016, 5:01:14 AM5/17/16
to elm-d...@googlegroups.com

Add this as a comment on the GitHub issue, then?

Richard Osafo

unread,
May 17, 2016, 8:56:19 AM5/17/16
to Elm Discuss
@Janis
Thanks. It is the same issue. Not a show stopper though since a simple `if` fixes it.

@Fedor
Indeed but in that case, don't you think Json.Decode.succeed and Json.Decode.fail must be updated to point that out? When you do `oneOf` with `succeed` in it, you naturally expect it to work as that is what the documentation says.
Reply all
Reply to author
Forward
0 new messages