Parsing JSON string into record in Haskell

前端 未结 5 2150
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 10:42

I\'m struggling to understand this (I\'m still a bit new to Haskell) but I\'m finding the documentation for the Text.JSON package to be a little confusing. Basicall

5条回答
  •  悲哀的现实
    2021-01-31 11:21

    You need to write a showJSON and readJSON method, for your type, that builds your Haskell values out of the JSON format. The JSON package will take care of parsing the raw string into a JSValue for you.

    Your tweet will be a JSObject containing a map of strings, most likely.

    • Use show to look at the JSObject, to see how the fields are laid out.
    • You can lookup each field using get_field on the JSObject.
    • You can use fromJSString to get a regular Haskell strings from a JSString.

    Broadly, you'll need something like,

    {-# LANGUAGE RecordWildCards #-}
    
    import Text.JSON
    import Text.JSON.Types
    
    instance JSON Tweet where
    
        readJSON (JSObject o) = return $ Tweet { .. }
                where from_user         = grab o "from_user"
                      to_user_id        = grab o "to_user_id"
                      profile_image_url = grab o "proile_image_url"
                      created_at        = grab o "created_at"
                      id_str            = grab o "id_str"
                      source            = grab o "source"
                      to_user_id_str    = grab o "to_user_id_str"
                      from_user_id_str  = grab o "from_user_id_str"
                      from_user_id      = grab o "from_user_id"
                      text              = grab o "text"
                      metadata          = grab o "metadata"
    
    
    grab o s = case get_field o s of
                    Nothing            -> error "Invalid field " ++ show s
                    Just (JSString s') -> fromJSString s'
    

    Note, I'm using the rather cool wild cards language extension.

    Without an example of the JSON encoding, there's not much more I can advise.


    Related

    You can find example instances for the JSON encoding via instances

    • in the source, for simple types. Or in other packages that depend on json.
    • An instance for AUR messages is here, as a (low level) example.

提交回复
热议问题