FromJSON make a list from multiple fields

前端 未结 2 1080
孤街浪徒
孤街浪徒 2021-01-21 10:56

I have an object to parse that looks a bit like this :

{
  \"data\":
  [
    {
      \"virtio0\": \"some text\",
      \"virtio1\": \"blah\",
      \"ide2\": \"s         


        
2条回答
  •  执念已碎
    2021-01-21 11:03

    If as you said there are only 9 virtio and 2 ide, one simple and perhaps not so elegent way to do is to use the asum function from Data.Foldable (which is generalised choice from various parsing libraries)

    import Control.Applicative
    
    
    instance FromJSON VM where
      parseJSON = withObject "VM" $ \o -> do
        cores <- o .: "cores"
        mem   <- o .: "mem"
        disk  <- optional $ asum [
          o .: "virtio0",
          o .: "virtio1",
          o .: "virtio2",
        return VM{..}
    

    I haven't tried the code yet. For further reference, see this link for a comprehensive guide of haskell JSON parsing with the Aeson library.

提交回复
热议问题