Search code examples
purescriptargonaut

Parse JSON in PureScript with Argonaut


I use argonaut library in PureScript for decode and encode JSON. I cannot write an implementation to decode and encode such json field:

"field": [3, "text"]

Here's an array with different data types. How can I instance it in argonaut library?


Solution

  • If you have a fixed number of values of different types, this is generally (in computer science and mathematics) called a "tuple", with a special name for when there are just two of them - a "pair".

    JavaScript doesn't have a concept of a tuple, and admittedly it would make little sense in the absence of static types. So traditionally tuples in JavaScript are encoded as arrays.

    But PureScript does have such concept! In the standard library it's called - surprise! - Tuple (and then there are variants for different number of elements - Tuple3, Tuple4, and so on)

    And Argonaut follows the JavaScript convention: it encodes tuples as arrays. So if you just type your field as a Tuple Int String, it will work:

    type MyObj = { field :: Tuple Int String }
    
    x :: Either JsonDecodeError MyObj
    x = parseJson "{ \"field\": [3, \"text\"] }" >>= decodeJson
    
    main :: Effect Unit
    main = 
      logShow x  -- prints Right { field: Tuple 3 "text" }