Aeson: derive some (but not all) fields of a struct












2














I have a large struct which I need to be an instance of FromJSON so that I can parse my json data into it.



I would like to derive automatically, but a single field needs "special care" in that it is an object in json and I want it to be an array of the values in my struct. How can I do this without writing a huge FromJson implementation repeating all the fields?



Example json:



{"myobject": {"one": 1, "two": 2}, ...many_more_fields...}


Example struct:



data MyStruct = MyStruct {
myobject :: [Int],
...many_more_fields,...
} deriving (Generic)


How do I do this elegantly?










share|improve this question






















  • related: stackoverflow.com/questions/53352563/…
    – assembly.jc
    Nov 23 '18 at 15:42
















2














I have a large struct which I need to be an instance of FromJSON so that I can parse my json data into it.



I would like to derive automatically, but a single field needs "special care" in that it is an object in json and I want it to be an array of the values in my struct. How can I do this without writing a huge FromJson implementation repeating all the fields?



Example json:



{"myobject": {"one": 1, "two": 2}, ...many_more_fields...}


Example struct:



data MyStruct = MyStruct {
myobject :: [Int],
...many_more_fields,...
} deriving (Generic)


How do I do this elegantly?










share|improve this question






















  • related: stackoverflow.com/questions/53352563/…
    – assembly.jc
    Nov 23 '18 at 15:42














2












2








2


1





I have a large struct which I need to be an instance of FromJSON so that I can parse my json data into it.



I would like to derive automatically, but a single field needs "special care" in that it is an object in json and I want it to be an array of the values in my struct. How can I do this without writing a huge FromJson implementation repeating all the fields?



Example json:



{"myobject": {"one": 1, "two": 2}, ...many_more_fields...}


Example struct:



data MyStruct = MyStruct {
myobject :: [Int],
...many_more_fields,...
} deriving (Generic)


How do I do this elegantly?










share|improve this question













I have a large struct which I need to be an instance of FromJSON so that I can parse my json data into it.



I would like to derive automatically, but a single field needs "special care" in that it is an object in json and I want it to be an array of the values in my struct. How can I do this without writing a huge FromJson implementation repeating all the fields?



Example json:



{"myobject": {"one": 1, "two": 2}, ...many_more_fields...}


Example struct:



data MyStruct = MyStruct {
myobject :: [Int],
...many_more_fields,...
} deriving (Generic)


How do I do this elegantly?







json haskell aeson






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 15:01









Marius Melzer

466




466












  • related: stackoverflow.com/questions/53352563/…
    – assembly.jc
    Nov 23 '18 at 15:42


















  • related: stackoverflow.com/questions/53352563/…
    – assembly.jc
    Nov 23 '18 at 15:42
















related: stackoverflow.com/questions/53352563/…
– assembly.jc
Nov 23 '18 at 15:42




related: stackoverflow.com/questions/53352563/…
– assembly.jc
Nov 23 '18 at 15:42












2 Answers
2






active

oldest

votes


















3














You should create a newtype for your special field:



newtype MySpecialType = MySpecialType [Int]

instance FromJSON MySpecialType where ....

data MyStruct = MyStruct {
myobject:: MySpecialType,
...
}


Now the instance for MyStruct becomes entirely regular and can be handed off to Template Haskell in the normal way.






share|improve this answer





























    0














    To avoid carrying the newtype from Paul Johnson's very good answer all across the codebase, you can also generalize your type as follows, making the type of myobject a parameter:



    data MyStruct_ intList = MyStruct {
    myobject :: intlist,
    ...
    } deriving (Functor, Generic)

    type MyStruct = MyStruct [Int]

    instance FromJSON MyStruct where
    parseJSON = (fmap . fmap) ((MySpecialType i) -> i)
    . genericParseJSON defaultOptions


    genericParseJSON above gets instantiated with MyStruct MySpecialType, and then the field gets unwrapped via fmap (noting MyStruct_ is a Functor)





    I also just wrote a blogpost about "type surgery", applied to this kind of problem so that you can keep the original type unmodified.



    The generic-data-surgery library can derive a generic type with the same Generic structure as MyStruct_ MySpecialType above, to be used by aeson's genericParseJSON. The surgery modifyRField then applies the function (MySpecialType i) -> i to the myobject field, finally yielding MyStruct.



    import Generic.Data.Surgery (fromOR, toOR', modifyRField)

    -- The original type
    data MyStruct = MyStruct {
    myobject :: [Int],
    ...
    } deriving (Generic)

    instance FromJSON MyStruct where
    parseJSON = fmap (fromOR . modifyRField @"myobject" ((MySpecialType i) -> i) . toOR')
    . genericParseJSON defaultOptions





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448958%2faeson-derive-some-but-not-all-fields-of-a-struct%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      You should create a newtype for your special field:



      newtype MySpecialType = MySpecialType [Int]

      instance FromJSON MySpecialType where ....

      data MyStruct = MyStruct {
      myobject:: MySpecialType,
      ...
      }


      Now the instance for MyStruct becomes entirely regular and can be handed off to Template Haskell in the normal way.






      share|improve this answer


























        3














        You should create a newtype for your special field:



        newtype MySpecialType = MySpecialType [Int]

        instance FromJSON MySpecialType where ....

        data MyStruct = MyStruct {
        myobject:: MySpecialType,
        ...
        }


        Now the instance for MyStruct becomes entirely regular and can be handed off to Template Haskell in the normal way.






        share|improve this answer
























          3












          3








          3






          You should create a newtype for your special field:



          newtype MySpecialType = MySpecialType [Int]

          instance FromJSON MySpecialType where ....

          data MyStruct = MyStruct {
          myobject:: MySpecialType,
          ...
          }


          Now the instance for MyStruct becomes entirely regular and can be handed off to Template Haskell in the normal way.






          share|improve this answer












          You should create a newtype for your special field:



          newtype MySpecialType = MySpecialType [Int]

          instance FromJSON MySpecialType where ....

          data MyStruct = MyStruct {
          myobject:: MySpecialType,
          ...
          }


          Now the instance for MyStruct becomes entirely regular and can be handed off to Template Haskell in the normal way.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 15:13









          Paul Johnson

          13.5k23449




          13.5k23449

























              0














              To avoid carrying the newtype from Paul Johnson's very good answer all across the codebase, you can also generalize your type as follows, making the type of myobject a parameter:



              data MyStruct_ intList = MyStruct {
              myobject :: intlist,
              ...
              } deriving (Functor, Generic)

              type MyStruct = MyStruct [Int]

              instance FromJSON MyStruct where
              parseJSON = (fmap . fmap) ((MySpecialType i) -> i)
              . genericParseJSON defaultOptions


              genericParseJSON above gets instantiated with MyStruct MySpecialType, and then the field gets unwrapped via fmap (noting MyStruct_ is a Functor)





              I also just wrote a blogpost about "type surgery", applied to this kind of problem so that you can keep the original type unmodified.



              The generic-data-surgery library can derive a generic type with the same Generic structure as MyStruct_ MySpecialType above, to be used by aeson's genericParseJSON. The surgery modifyRField then applies the function (MySpecialType i) -> i to the myobject field, finally yielding MyStruct.



              import Generic.Data.Surgery (fromOR, toOR', modifyRField)

              -- The original type
              data MyStruct = MyStruct {
              myobject :: [Int],
              ...
              } deriving (Generic)

              instance FromJSON MyStruct where
              parseJSON = fmap (fromOR . modifyRField @"myobject" ((MySpecialType i) -> i) . toOR')
              . genericParseJSON defaultOptions





              share|improve this answer


























                0














                To avoid carrying the newtype from Paul Johnson's very good answer all across the codebase, you can also generalize your type as follows, making the type of myobject a parameter:



                data MyStruct_ intList = MyStruct {
                myobject :: intlist,
                ...
                } deriving (Functor, Generic)

                type MyStruct = MyStruct [Int]

                instance FromJSON MyStruct where
                parseJSON = (fmap . fmap) ((MySpecialType i) -> i)
                . genericParseJSON defaultOptions


                genericParseJSON above gets instantiated with MyStruct MySpecialType, and then the field gets unwrapped via fmap (noting MyStruct_ is a Functor)





                I also just wrote a blogpost about "type surgery", applied to this kind of problem so that you can keep the original type unmodified.



                The generic-data-surgery library can derive a generic type with the same Generic structure as MyStruct_ MySpecialType above, to be used by aeson's genericParseJSON. The surgery modifyRField then applies the function (MySpecialType i) -> i to the myobject field, finally yielding MyStruct.



                import Generic.Data.Surgery (fromOR, toOR', modifyRField)

                -- The original type
                data MyStruct = MyStruct {
                myobject :: [Int],
                ...
                } deriving (Generic)

                instance FromJSON MyStruct where
                parseJSON = fmap (fromOR . modifyRField @"myobject" ((MySpecialType i) -> i) . toOR')
                . genericParseJSON defaultOptions





                share|improve this answer
























                  0












                  0








                  0






                  To avoid carrying the newtype from Paul Johnson's very good answer all across the codebase, you can also generalize your type as follows, making the type of myobject a parameter:



                  data MyStruct_ intList = MyStruct {
                  myobject :: intlist,
                  ...
                  } deriving (Functor, Generic)

                  type MyStruct = MyStruct [Int]

                  instance FromJSON MyStruct where
                  parseJSON = (fmap . fmap) ((MySpecialType i) -> i)
                  . genericParseJSON defaultOptions


                  genericParseJSON above gets instantiated with MyStruct MySpecialType, and then the field gets unwrapped via fmap (noting MyStruct_ is a Functor)





                  I also just wrote a blogpost about "type surgery", applied to this kind of problem so that you can keep the original type unmodified.



                  The generic-data-surgery library can derive a generic type with the same Generic structure as MyStruct_ MySpecialType above, to be used by aeson's genericParseJSON. The surgery modifyRField then applies the function (MySpecialType i) -> i to the myobject field, finally yielding MyStruct.



                  import Generic.Data.Surgery (fromOR, toOR', modifyRField)

                  -- The original type
                  data MyStruct = MyStruct {
                  myobject :: [Int],
                  ...
                  } deriving (Generic)

                  instance FromJSON MyStruct where
                  parseJSON = fmap (fromOR . modifyRField @"myobject" ((MySpecialType i) -> i) . toOR')
                  . genericParseJSON defaultOptions





                  share|improve this answer












                  To avoid carrying the newtype from Paul Johnson's very good answer all across the codebase, you can also generalize your type as follows, making the type of myobject a parameter:



                  data MyStruct_ intList = MyStruct {
                  myobject :: intlist,
                  ...
                  } deriving (Functor, Generic)

                  type MyStruct = MyStruct [Int]

                  instance FromJSON MyStruct where
                  parseJSON = (fmap . fmap) ((MySpecialType i) -> i)
                  . genericParseJSON defaultOptions


                  genericParseJSON above gets instantiated with MyStruct MySpecialType, and then the field gets unwrapped via fmap (noting MyStruct_ is a Functor)





                  I also just wrote a blogpost about "type surgery", applied to this kind of problem so that you can keep the original type unmodified.



                  The generic-data-surgery library can derive a generic type with the same Generic structure as MyStruct_ MySpecialType above, to be used by aeson's genericParseJSON. The surgery modifyRField then applies the function (MySpecialType i) -> i to the myobject field, finally yielding MyStruct.



                  import Generic.Data.Surgery (fromOR, toOR', modifyRField)

                  -- The original type
                  data MyStruct = MyStruct {
                  myobject :: [Int],
                  ...
                  } deriving (Generic)

                  instance FromJSON MyStruct where
                  parseJSON = fmap (fromOR . modifyRField @"myobject" ((MySpecialType i) -> i) . toOR')
                  . genericParseJSON defaultOptions






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 26 '18 at 14:44









                  Li-yao Xia

                  11.5k1327




                  11.5k1327






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448958%2faeson-derive-some-but-not-all-fields-of-a-struct%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks