Search code examples
haskellaeson

Access a json values by their key


I want to get a value from a json object using a key

      let nm = case rep_json of
            Object v -> case HM.lookup "names" v of
              Just endps -> Just v
              _ -> Nothing
            _ -> Nothing

This doesn't work, I get this error

Couldn't match type: Data.Aeson.KeyMap.KeyMap Value with: HashMap k0 v0 Expected: HashMap k0 v0 Actual: Objec In the second argument of ‘HM.lookup’, namely v


Solution

  • Objects used to have hashmaps in them, but don't in the most recent versions. They now contain an abstract KeyMap type. I don't know why they changed for sure but I wouldn't be surprised if it was to give a new type to hang class instances on. You can see more in the documentation here; in most cases you just need to change which module you get your operations from (i.e. your HM.lookup -> Data.Aeson.KeyMap.lookup).