1

I need to get all the keys in a given object this is how I managed to do it.

{-# LANGUAGE DeriveGeneric #-}

import System.Environment
import Data.Aeson
import Data.Foldable
import GHC.Generics
import qualified Data.HashMap.Strict as Hashmap

data Person = Person {
    name :: String,
    age::Int
} deriving (Generic,Show)

instance ToJSON Person

main=do
    let p = Person "random" 100
    let obj = decode(encode p)::Maybe Object
    case obj of
        (Just x) -> do
            let keysOfObject = Hashmap.keys x
            print keysOfObject
        _ -> print "failed to decode"

output: ["age","name"]

Is there a better(easier) way of doing this

vijaicv
  • 535
  • 5
  • 9
  • 1
    Yes, there's a better way. But probably the correct answer is "don't do this". What comes next, once you have the "keys" available? What are you going to do with them? Perhaps we can advise you on a way to just do that without fetching the "keys" first. – Daniel Wagner Nov 17 '21 at 04:15
  • Daniel Wagner - I have a config.json file which I am going to parse using aeson to this type, but in the absence of such a file I want take values from the env vars so I need to know what are the properties to look for So I need the list of keys . – vijaicv Nov 17 '21 at 05:52
  • 1
    Okay. Either write the environment parser manually or read about generic programming. The current route is going to have way more headaches than you think it will, including: you need a way to convert the `String` in the environment variable into the right type for the named field (e.g. `Int` for `age`); you need to have a way to assemble the mapping from field names to fields into a `Person`; you need to handle types with fields but no field names; you need to handle types with multiple constructors. `Person <$> env "NAME" <*> (read <$> env "AGE")` really isn't that bad by comparison. – Daniel Wagner Nov 17 '21 at 06:02
  • It sounds like you think that a Haskell type is like a JavaScript or Python object. It isn't. – Paul Johnson Nov 17 '21 at 11:55

0 Answers0