Search code examples
jsonpurescriptargonaut

purescript-argonaut: Decode arbitrary key-value json


Is there a way to decode arbitrary json (e.g: We don't know the keys at compile time)?

For example, I need to parse the following json:

{ 
    "Foo": [
        "Value 1",
        "Value 2"
    ],
    "Bar": [
        "Bar Value 1"
    ],
    "Baz": []
}

where the names and number of keys are not known at compile time and may change per GET request. The goal is basically to decode this into a Map String (Array String) type

Is there a way to do this using purescript-argonaut?


Solution

  • You can totally write your own by first parsing the string into Json via jsonParser, and then examining the resulting data structure with the various combinators provided by Argonaut.

    But the quickest and simplest way, I think, is to parse it into Foreign.Object (Array String) first, and then convert to whatever your need, like Map String (Array String):

    import Data.Argonaut (decodeJson, jsonParser)
    import Data.Either (Either)
    import Data.Map as Map
    import Foreign.Object as F
    
    decodeAsMap :: String -> Either _ (Map.Map String (Array String))
    decodeAsMap str = do
        json <- jsonParser str
        obj <- decodeJson json
        pure $ Map.fromFoldable $ (F.toUnfoldable obj :: Array _)