json parsing in haskell

后端 未结 2 1126
心在旅途
心在旅途 2020-12-30 04:15

I\'m trying to parse JSON data in haskell. Having gone through a slew of websites, this is the furthest I have been able to get to.

data Address = Address {          


        
2条回答
  •  渐次进展
    2020-12-30 04:37

    Maybe a bit late in the game, but since this is the first page google returns I'll give it a go.

    Aeson is the defacto standard these days so that's the library everybody uses. The Aeson TH package offers some nice functionality for automatically generating the necessary functions for your custom data types.

    Basically you create your data types that correspond to the json data and then let aeson do the magic.

    {-# LANGUAGE OverloadedStrings,TemplateHaskell #-}
    import Data.Aeson
    import Data.Aeson.TH
    import qualified Data.ByteString.Lazy.Char8 as BL
    
    data Address = Address
        { house  :: Integer
        , street :: String
        , city   :: String
        , state  :: Maybe String
        , zip    :: Integer
        } deriving (Show, Eq)
    
    data Person = Person
        { name    :: String
        , age     :: Integer
        , address :: Address
        } deriving (Show, Eq)
    
    $(deriveJSON defaultOptions ''Address)
    $(deriveJSON defaultOptions ''Person)
    
    aa :: BL.ByteString
    aa = "{\"name\": \"some body\", \"age\" : 23, \"address\" : {\"house\" : 285, \"street\" : \"7th Ave.\", \"city\" : \"New York\", \"state\" : \"New York\", \"zip\" : 10001}}"
    
    main = print (decode aa :: Maybe Person)
    

    You can even have optional fields with the Maybe datatype.

提交回复
热议问题