Just v _ -> Nothi" /> Just v _ -> Nothi" /> Just v _ -> Nothi"/>

Access a json values by their key

70 Views Asked by At

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

2

There are 2 best solutions below

0
Daniel Wagner On BEST ANSWER

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).

1
willeM_ Van Onsem On

In previous versions of , this would have worked. Since aeson-2.0.0.0 however, aeson no longer works with a HashMap, but with its own KeyMap, and hence you can not work with the lookup of a HashMap.

You however probably don't need to implement this manually. Indeed, you can work with lenses of the lens-aeson package [hackage]. You can look up a key with key :: AsValue t => Key -> Traversal' t Value:

{-# LANGUAGE OverloadedStrings #-}

import Control.Lens.Fold ((^?))
import Data.Aeson (Value)
import Data.Aeson.Lens (key)

my_value :: Maybe Value
my_value = rep_json ^? key "names"