Skip to content

Instantly share code, notes, and snippets.

@cdparks
Created October 1, 2018 09:58
Show Gist options
  • Save cdparks/32217e570048dd2066549272b1640b5b to your computer and use it in GitHub Desktop.
Save cdparks/32217e570048dd2066549272b1640b5b to your computer and use it in GitHub Desktop.
Structurally similar JSON payloads using a nested record
#!/usr/bin/env stack
-- stack --resolver lts-12.8 ghci
{-
> main
Record1 {z = 3, xy1 = Common {x = 1, y = 2}}
Record2 {w = 3, xy2 = Common {x = 1, y = 2}}
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Common where
import Data.Aeson
data Common = Common
{ x :: Int
, y :: Int
} deriving (Eq, Show)
instance FromJSON Common where
parseJSON = withObject "Common" $ \o ->
Common <$> o .: "x" <*> o .: "y"
data Record1 = Record1
{ z :: Int
, xy1 :: Common
} deriving (Eq, Show)
instance FromJSON Record1 where
parseJSON = withObject "Record1" $ \o ->
Record1 <$> o .: "z" <*> parseJSON (Object o)
data Record2 = Record2
{ w :: Int
, xy2 :: Common
} deriving (Eq, Show)
instance FromJSON Record2 where
parseJSON = withObject "Record2" $ \o ->
Record2 <$> o .: "w" <*> parseJSON (Object o)
main :: IO ()
main = do
let
Just r1 :: Maybe Record1 = decode "{\"x\": 1, \"y\": 2, \"z\": 3}"
Just r2 :: Maybe Record2 = decode "{\"x\": 1, \"y\": 2, \"w\": 3}"
print r1
print r2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment