Ryan Monreal
Ryan Monreal

Reputation: 597

Return JSON based on Persistent Query from yesod handler

this will be an additional question for @KonstantineRybnikov about Return JSON from yesod handler.

What if i want have a Persistent Query specifically selectList and all the result data must return into a JSON format? what will be the code for it?

here is my code (Adopt from the code of @KonstantineRybnikov):

    -- JSON
    import           Data.Aeson      (object, (.=))
    import qualified Data.Aeson      as J
    import           Yesod.Core.Json (returnJson)

    getImagesR :: Handler Value
    getImagesR = do
          images <- runDB $ selectList [ImagesFilename !=. ""] [Desc ImagesDate]
          return $ object (if null images then [] else [] -- i want the result of my perstent to be in a JSON FORMAT)

``

hope you help me thank you.

Upvotes: 1

Views: 422

Answers (1)

madjar
madjar

Reputation: 12951

I guess your main problem is that selectList returns a list of Entity Record (where Record is the type you are querying) instead of Record, so we'll have to get a list of records using map entityVal (entityVal is defined in Entity). You handler will look like this :

getImagesR = do
  images <- runDB $ selectList [ImagesFilename !=. ""] [Desc ImagesDate]
  returnJson (map entityVal images)

Now it's just a matter of transforming [Record] to JSON. Luckily, this can be done automatically by adding the word json to the persistent model definition (as shown here).

Upvotes: 1

Related Questions