Contact/support | Changelog

extract json stuff

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.ByteString.Lazy.Char8() 
import Control.Monad

foo = "{\"response\":[25343,{\"aid\":87537405,\"owner_id\":19890745,\"artist\":\"Keane\",\"title\":\"Somewhere Only We Know (OST LOL)\226\153\165\226\153\165\226\153\165\",\"duration\":237,\"url\":\"http:$

bar :: [(String, String)]
bar = x where (Just (Stuff x)) = decode foo

data Stuff = Stuff [(String, String)] deriving (Show)

instance FromJSON Stuff where
    parseJSON (Object v) = do
        response  <- v .: "response"
        result <- forM (drop 1 response) $ \(Object item) -> do
            title <- item .: "title"
            url <- item .: "url"
            return (title, url)
        return $ Stuff result

main = print bar         

extract json stuff (annotation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.ByteString.Lazy.Char8()
import Control.Monad
import Control.Applicative

import Data.Aeson.Types
import Data.Aeson.Parser (value)
import Data.Attoparsec.ByteString (parseOnly)
import qualified Data.ByteString as BS

extract :: (Value -> Parser a) -> BS.ByteString -> Either String a
extract parser dat = either Left (parseEither parser) $ parseOnly value dat

foo = "{\"response\":[25343,{\"aid\":87537405,\"owner_id\":19890745,\"artist\":\"Keane\",\"title\":\"Somewhere Only We Know (OST LOL)\226\153\165\226\153\165\226\153\165\",\"duration\":237,\"url\":\"http:\\/\\/cs4588.userapi.com\\/u63234245\\/audios\\/6a87713c6b1d.mp3\",\"lyrics_id\":\"3251001\"},{\"aid\":115278459,\"owner_id\":142550998,\"artist\":\"The Prodigy vs. Cut&Run vs. Black Eyed Peas vs. Far East Movement vs. Super Mario Brothers\",\"title\":\"Outta Space like a G6 (Dirty Bit) vk.com\\/id80190000 rap guf house trance techno dubstep lol drum bass sensation mix rmx remix music dance 2010 2011 2012 new now kazantip \208\191\208\190\208\178\208\176\",\"duration\":280,\"url\":\"http:\\/\\/cs4995.userapi.com\\/u12326667\\/audios\\/468386df517a.mp3\",\"lyrics_id\":\"17241947\"},{\"aid\":156628254,\"owner_id\":17970457,\"artist\":\"Rock Mafia\",\"title\":\"The Big Bang (OST \208\155\208\181\209\130\208\190. \208\158\208\180\208\189\208\190\208\186\208\187\208\176\209\129\209\129\208\189\208\184\208\186\208\184. \208\155\209\142\208\177\208\190\208\178\209\140 \\/ LOL)\",\"duration\":167,\"url\":\"http:\\/\\/cs5122.userapi.com\\/u10433430\\/audios\\/c558757fd6cd.mp3\",\"lyrics_id\":\"25808933\"}]}"

bar = extract $ \(Object v) -> do
    response <- v .: "response"
    forM (drop 1 response) $ \(Object i) -> do
        title <- i .: "title"
        url <- i .: "url"
        return (title :: String, url :: String)

main = print $ bar foo