0

What's the Aeson equivalent of the javascript property accessor.

How would you translate the javascript statement x.a.b to Haskell?

As an example, given someObject :: Object containing e.g:

{ a:
  { b:
    [ 1
    , 2
    ]
  }
}

What would the function that returns [1,2] for the above look like.

I've searching around for an answer to this problem and it would appear the answer to this question is "use lenses". I just can't seem to figure out how to do this.

fredefox
  • 681
  • 3
  • 11

1 Answers1

1

Here is a lens solution:

 {-# LANGUAGE OverloadedStrings #-}

 import Data.Text
 import Data.Aeson
 import Data.Aeson.Lens
 import Control.Lens

 Just obj1 = decode ("{ \"a\": { \"b\": [ 3,4,5] } }" ) :: Maybe Value
 Just obj2 = decode ("{ \"a\": { \"d\": true } }" ) :: Maybe Value

 test1 = (Just obj1) ^. (key "a" ) ^. (key "b") :: Maybe Value
 test2 = (Just obj2) ^. (key "a" ) ^. (key "b") :: Maybe Value

Note that you have to start the chain with a Maybe Value.

Here's a non-lens answer if that helps:

 {-# LANGUAGE OverloadedStrings #-}

 import Data.Aeson
 import qualified Data.HashMap.Strict as HM

 -- access .a.b
 get_a_b :: Object -> Maybe Value
 get_a_b hm = do
   v <- HM.lookup "a" hm
   hm2 <- case v of
            (Object hm2) -> return hm2
            _            -> Nothing
   HM.lookup "b" hm2
ErikR
  • 51,541
  • 9
  • 73
  • 124