Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode tuple to JSON in elm

I have tuple of (String,Bool) that need to be encoded to JSON Array in elm.

This below link is useful for the primitive types and other list, array and object. But I need to encode tuple2.

Refer : http://package.elm-lang.org/packages/elm-lang/core/4.0.3/Json-Encode#Value

I tried different approach like encoding tuple with toString function. It does not gives me JSON Array instead it produces String as below "(\"r"\,False)".

JSON.Decoder expecting the input paramater to decode as below snippet.

decodeString (tuple2 (,) float float) "[3,4]"

Refer : http://package.elm-lang.org/packages/elm-lang/core/4.0.3/Json-Decode

Q : When there is decode function available for tuple2, why encode function is missing it.

like image 584
Ranjith Raj D Avatar asked Dec 06 '22 17:12

Ranjith Raj D


1 Answers

You can build a generalized tuple size 2 encoder like this:

import Json.Encode exposing (..)

tuple2Encoder : (a -> Value) -> (b -> Value) -> (a, b) -> Value
tuple2Encoder enc1 enc2 (val1, val2) =
  list [ enc1 val1, enc2 val2 ]

Then you can call it like this, passing the types of encoders you want to use for each slot:

tuple2Encoder string bool ("r", False)
like image 194
Chad Gilbert Avatar answered Dec 15 '22 08:12

Chad Gilbert