Skip to content

Instantly share code, notes, and snippets.

@bitemyapp
Forked from louissalin/gist:e9713582aa83a0cfa446
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save bitemyapp/bf9c037ef128d6abad12 to your computer and use it in GitHub Desktop.

Select an option

Save bitemyapp/bf9c037ef128d6abad12 to your computer and use it in GitHub Desktop.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment