Skip to content

Instantly share code, notes, and snippets.

@louissalin
Created January 13, 2015 19:58
Show Gist options
  • Save louissalin/e9713582aa83a0cfa446 to your computer and use it in GitHub Desktop.
Save louissalin/e9713582aa83a0cfa446 to your computer and use it in GitHub Desktop.
experimenting with parseMaybe

using this Aeson example:

do result <- decode "{\"name\":\"Dave\",\"age\":2}"
      flip parseMaybe result $ \obj -> do
        age <- obj .: "age"
        name <- obj .: "name"
        return (name ++ ": " ++ show (age*2))

Just "Dave: 4"

The JSON string I'm trying to parse looks like this: { courses: [{id: 123, ...}, ...] }

I was wondering how to deal with lists, so I tried to cause type errors hoping the compiler would help out. But this compiled just fine.

getJsonCourseId' :: LB.ByteString -> Maybe Int
getJsonCourseId' body = do
  result <- decode body
  inners <- flip parseMaybe result $ \obj -> do
    entities <- obj .: "courses"
    return $ entities
  flip parseMaybe inners $ \objs -> do
    id <- objs .: "id"
    return id
@bitemyapp
Copy link

getJsonCourseId' :: LByteString -> Maybe Int
getJsonCourseId' body = do
  result <- decode body
  flip parseMaybe result $ \obj -> do
    entities <- obj .: "courses"
    id' <- entities .: "id"
    return id'

should work just the same, right?

@louissalin
Copy link
Author

yes, it should.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment