Haskell: Reusing FromJSON instances with lenses, lens-aeson, and nested JSON

后端 未结 1 998
[愿得一人]
[愿得一人] 2021-02-04 15:13

I have been playing with Aeson and the lens package (lens-aeson, migrated from the core lens package), and have been sruggling to get them to work together.

As a toy exa

相关标签:
1条回答
  • 2021-02-04 15:56

    You can use the _JSON prism. You only need to write a ToJSON instance for Colour:

    instance ToJSON Colour where
      toJSON Yellow = String "yellow"
      toJSON Blue   = String "blue"
      toJSON Green  = String "green"
    

    and then you can use it like this:

    parseColour :: String -> Maybe Colour
    parseColour j = j ^? key "info" . key "colour" . _JSON
    -- point-free: parseColor = preview $ key "info" . key "colour" . _JSON
    
    -- In GHCi
    λ: parseColour "{ \"info\": { \"colour\": \"yellow\" } }"
    Just Yellow
    
    0 讨论(0)
提交回复
热议问题