I'm trying to reduce nested JSON data using Haskell and Aeson without creating data/record types.
The following code works, but seems ugly and unreadable.
Any advice on cleaning this up would be great.
Thank you
import GHC.Exts
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.Aeson
import qualified Data.HashMap.Strict as M
testVal :: Value
testVal = Object $ fromList [
("items", Array $ fromList [
(Object $ fromList [
("entity", (Object $ fromList [
("uuid", String "needed-value1")]))]),
(Object $ fromList [
("entity", (Object $ fromList [
("uuid", String "needed-value2")]))])
])]
getItems :: Value -> Value
getItems (Object o) = fromJust $ M.lookup "items" o
getEntities :: Value -> Value
getEntities (Array a) = Array $ fmap (\(Object o) -> fromJust $ M.lookup "entity" o) a
getUuids :: Value -> Value
getUuids (Array a) = Array $ fmap (\(Object o) -> fromJust $ M.lookup "uuid" o) a
getTexts :: Value -> [Text]
getTexts (Array a) = toList $ fmap (\(String s) -> s) a
someFunc :: IO ()
someFunc = do
let items = getItems testVal
entities = getEntities items
uuids = getUuids entities
texts = getTexts uuids
print texts
output:
["needed-value1","needed-value2"]
FromJSONinstances. This will make your code way cleaner. Could you also provide a sample JSON string that you want to parse? \$\endgroup\$