Elm: JSON decoder, convert String to Bool

我只是一个虾纸丫 提交于 2019-12-06 13:09:41

There are a few problems in your example so let's step through each of them.

You haven't shown the definition of Props so I'm assuming, based on your example, that it is this:

type alias Props = { name : String, value : Bool }

You are passing (,) as the first argument to object2 which indicates that you will be returning a Decoder of type tuple. That should probably be:

Json.Decode.object2 Props

Now, the way you are using andThen won't compile because of its order of precedence. If you were to parenthesize the whole thing, it would look like this:

userProperties =
  (Json.Decode.object2 Props
    ("name" := Json.Decode.string)
    ("value" := Json.Decode.string))
      `andThen` \val ->
        let
          newVal = -- Do something here?
        in
          Json.Decode.succeed <| newVal

That isn't going to be correct since the thing you want to andThen is the string "true" in the "value" field. To do that, I would recommend creating a decoder which provides that boolean decoder:

stringBoolDecoder : Json.Decode.Decoder Bool
stringBoolDecoder =
  string `andThen` \val ->
    case val of
      "true" -> succeed True
      "false" -> succeed False
      _ -> fail <| "Expecting \"true\" or \"false\" but found " ++ val

I'm only guessing at the handling of "false" and the catch-all underscore. Change their implementation as suits your business case.

When building complex decoders, it is often best to break up decoder definitions into the smallest chunk possible like in the above.

Lastly, we can now redefine your userProperties decoder to use the stringBoolDecoder in the appropriate place:

userProperties : Json.Decode.Decoder Props
userProperties =
  Json.Decode.object2 Props
    ("name" := Json.Decode.string)
    ("value" := stringBoolDecoder)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!