I'm receiving a JSON that looks like this:
{ name: "NAME1", value: "true" }
I would like to create a json decoder that would create a record like this:
{ name: "NAME1", value: True }
I'm trying to make a decoder that transforms "true" into True. I did this so far:
userProperties : Json.Decode.Decoder Props
userProperties =
Json.Decode.object2 (,)
("name" := Json.Decode.string)
("value" := Json.Decode.string)
`andThen` \val ->
let
newVal = -- Do something here?
in
Json.Decode.succeed <| newVal
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)
来源:https://stackoverflow.com/questions/37157902/elm-json-decoder-convert-string-to-bool