JSON selector class in PythonJSON templates in PythonCritique my JSON-optimizing Python scriptAutocomplete...

Does this Wild Magic result affect the sorcerer or just other creatures?

Are all instances of trolls turning to stone ultimately references back to Tolkien?

Inaccessible base class despite friendship

What does the hyphen "-" mean in "tar xzf -"?

Greeting with "Ho"

Unusual mail headers, evidence of an attempted attack. Have I been pwned?

Is "Busen" just the area between the breasts?

Cut the gold chain

What's the difference between a deep fryer and a chip pan?

How to draw this center trajectory of rolling ball?

How does the spell Remove Curse interact with a Sword of Vengeance?

Impossible darts scores

Why use cross notes in sheet music for hip hop tracks?

Why does Linux list NVMe drives as /dev/nvme0 instead of /dev/sda?

Array initialization optimization

Are all Ringwraiths called Nazgûl in LotR?

Why does the Saturn V have standalone inter-stage rings?

Trainee keeps missing deadlines for independent learning

How does a blind passenger not die, if driver becomes unconscious

Can any NP-Complete Problem be solved using at most polynomial space (but while using exponential time?)

Loss of power when I remove item from the outlet

Is it illegal to withhold someone's passport and green card in California?

What is "industrial ethernet"?

Interaction between Leyline of Anticipation and Teferi, Time Raveler



JSON selector class in Python


JSON templates in PythonCritique my JSON-optimizing Python scriptAutocomplete Trie OptimizationJSON serialization helper classNewtonsoft Json helper classPrettify JSON classPretify JSON class -followupGet json format from sqlalchemy classExtracting the IP addresses of Docker containers using JSON APISimple class to handle Json






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2












$begingroup$


I've created a simple little class called JSONSelector to be able to select relevant data from a JSON object (a dict in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:



class JSONSelector:
def __init__(self, json):
self.json = json

def __str__(self):
return "{}({})".format(type(self).__name__, str(self.json))
__repr__ = __str__

def select(self, selectors):
if selectors == "*":
return type(self)(self.json)
else:
temp = {}
for sel in selectors:
temp[sel] = self.json.get(sel, None)
return type(self)(temp)

def where(self, cond):
temp = {}
for key, value in self.json.items():
if cond(key, value):
temp[key] = value
return type(self)(temp)

def astype(self, type_):
temp = {}
for key, value in self.json.items():
temp[key] = type_(value)
return JSONSelector(temp)

def sort(self, **kwargs):
return type(self)(dict(sorted(self.json.items(), **kwargs)))

def foreach(self, func):
for key, value in self.json.items():
if func(key, value) == False: break

def print(self, func=None):
if not func:
print(self)
return
else:
print(func(self))
return


Here's a test case with an explanation:



a = JSONSelector({
"stuff": 5,
"seeded": 6,
"number": "7",
"more_stuff": 8
})

a.select("*") # Select all entries from the dict
.where(lambda key,value: type(value) is int) # Where the value is an integer
.sort(key=lambda x: x[1]) # Sort by the value
.astype(str) # Convert the values to type str
.foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries


I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!










share|improve this question









$endgroup$



















    2












    $begingroup$


    I've created a simple little class called JSONSelector to be able to select relevant data from a JSON object (a dict in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:



    class JSONSelector:
    def __init__(self, json):
    self.json = json

    def __str__(self):
    return "{}({})".format(type(self).__name__, str(self.json))
    __repr__ = __str__

    def select(self, selectors):
    if selectors == "*":
    return type(self)(self.json)
    else:
    temp = {}
    for sel in selectors:
    temp[sel] = self.json.get(sel, None)
    return type(self)(temp)

    def where(self, cond):
    temp = {}
    for key, value in self.json.items():
    if cond(key, value):
    temp[key] = value
    return type(self)(temp)

    def astype(self, type_):
    temp = {}
    for key, value in self.json.items():
    temp[key] = type_(value)
    return JSONSelector(temp)

    def sort(self, **kwargs):
    return type(self)(dict(sorted(self.json.items(), **kwargs)))

    def foreach(self, func):
    for key, value in self.json.items():
    if func(key, value) == False: break

    def print(self, func=None):
    if not func:
    print(self)
    return
    else:
    print(func(self))
    return


    Here's a test case with an explanation:



    a = JSONSelector({
    "stuff": 5,
    "seeded": 6,
    "number": "7",
    "more_stuff": 8
    })

    a.select("*") # Select all entries from the dict
    .where(lambda key,value: type(value) is int) # Where the value is an integer
    .sort(key=lambda x: x[1]) # Sort by the value
    .astype(str) # Convert the values to type str
    .foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries


    I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!










    share|improve this question









    $endgroup$















      2












      2








      2


      2



      $begingroup$


      I've created a simple little class called JSONSelector to be able to select relevant data from a JSON object (a dict in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:



      class JSONSelector:
      def __init__(self, json):
      self.json = json

      def __str__(self):
      return "{}({})".format(type(self).__name__, str(self.json))
      __repr__ = __str__

      def select(self, selectors):
      if selectors == "*":
      return type(self)(self.json)
      else:
      temp = {}
      for sel in selectors:
      temp[sel] = self.json.get(sel, None)
      return type(self)(temp)

      def where(self, cond):
      temp = {}
      for key, value in self.json.items():
      if cond(key, value):
      temp[key] = value
      return type(self)(temp)

      def astype(self, type_):
      temp = {}
      for key, value in self.json.items():
      temp[key] = type_(value)
      return JSONSelector(temp)

      def sort(self, **kwargs):
      return type(self)(dict(sorted(self.json.items(), **kwargs)))

      def foreach(self, func):
      for key, value in self.json.items():
      if func(key, value) == False: break

      def print(self, func=None):
      if not func:
      print(self)
      return
      else:
      print(func(self))
      return


      Here's a test case with an explanation:



      a = JSONSelector({
      "stuff": 5,
      "seeded": 6,
      "number": "7",
      "more_stuff": 8
      })

      a.select("*") # Select all entries from the dict
      .where(lambda key,value: type(value) is int) # Where the value is an integer
      .sort(key=lambda x: x[1]) # Sort by the value
      .astype(str) # Convert the values to type str
      .foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries


      I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!










      share|improve this question









      $endgroup$




      I've created a simple little class called JSONSelector to be able to select relevant data from a JSON object (a dict in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:



      class JSONSelector:
      def __init__(self, json):
      self.json = json

      def __str__(self):
      return "{}({})".format(type(self).__name__, str(self.json))
      __repr__ = __str__

      def select(self, selectors):
      if selectors == "*":
      return type(self)(self.json)
      else:
      temp = {}
      for sel in selectors:
      temp[sel] = self.json.get(sel, None)
      return type(self)(temp)

      def where(self, cond):
      temp = {}
      for key, value in self.json.items():
      if cond(key, value):
      temp[key] = value
      return type(self)(temp)

      def astype(self, type_):
      temp = {}
      for key, value in self.json.items():
      temp[key] = type_(value)
      return JSONSelector(temp)

      def sort(self, **kwargs):
      return type(self)(dict(sorted(self.json.items(), **kwargs)))

      def foreach(self, func):
      for key, value in self.json.items():
      if func(key, value) == False: break

      def print(self, func=None):
      if not func:
      print(self)
      return
      else:
      print(func(self))
      return


      Here's a test case with an explanation:



      a = JSONSelector({
      "stuff": 5,
      "seeded": 6,
      "number": "7",
      "more_stuff": 8
      })

      a.select("*") # Select all entries from the dict
      .where(lambda key,value: type(value) is int) # Where the value is an integer
      .sort(key=lambda x: x[1]) # Sort by the value
      .astype(str) # Convert the values to type str
      .foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries


      I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!







      python json iteration






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 9 hours ago









      connectyourchargerconnectyourcharger

      2139




      2139






















          2 Answers
          2






          active

          oldest

          votes


















          3












          $begingroup$

          A few notes:



          Firstly I would add some docstrings to each function to document what the expected behaviour is.



          In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?



          In select, where, astype instead of creating a temporary dict you could use a dict comprehension instead, example:



          def where(self, cond):
          return type(self)({key: value for key, value in self.json.items() if cond(key, value)})


          In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.



          print seems like an unnecessary function, but if you keep it the return lines have no effect.



          Hope that's helpful.






          share|improve this answer








          New contributor



          bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          $endgroup$





















            2












            $begingroup$

            Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.



            Something closer to:



            def foreach(self, func):
            for key, value in self.json.items():
            should_continue = func(key, value)

            if should_continue == False:
            break


            If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:



            def foreach(self, func):
            for key, value in self.json.items():
            should_break = func(key, value)

            if should_continue:
            break




            I'm not sure there's much benefit to using your print method. I believe it's convoluting the simple task of just passing the object to print. If the user wants to pass some function before printing, just let them do it.



            As an example, what intuitively makes more sense to you?:



            json.print(str)


            or



            print(str(json))


            Personally, I find the latter to make more sense.



            I'll also note, your returns in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit return happens at the end of the method anyway.



            Finally, I don't think negating the condition in if not func helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:



            def print(self, func = None):
            if func:
            print(func(self))

            else:
            print(self)





            share|improve this answer











            $endgroup$
















              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: "196"
              };
              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: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              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%2fcodereview.stackexchange.com%2fquestions%2f222597%2fjson-selector-class-in-python%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












              $begingroup$

              A few notes:



              Firstly I would add some docstrings to each function to document what the expected behaviour is.



              In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?



              In select, where, astype instead of creating a temporary dict you could use a dict comprehension instead, example:



              def where(self, cond):
              return type(self)({key: value for key, value in self.json.items() if cond(key, value)})


              In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.



              print seems like an unnecessary function, but if you keep it the return lines have no effect.



              Hope that's helpful.






              share|improve this answer








              New contributor



              bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





              $endgroup$


















                3












                $begingroup$

                A few notes:



                Firstly I would add some docstrings to each function to document what the expected behaviour is.



                In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?



                In select, where, astype instead of creating a temporary dict you could use a dict comprehension instead, example:



                def where(self, cond):
                return type(self)({key: value for key, value in self.json.items() if cond(key, value)})


                In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.



                print seems like an unnecessary function, but if you keep it the return lines have no effect.



                Hope that's helpful.






                share|improve this answer








                New contributor



                bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                $endgroup$
















                  3












                  3








                  3





                  $begingroup$

                  A few notes:



                  Firstly I would add some docstrings to each function to document what the expected behaviour is.



                  In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?



                  In select, where, astype instead of creating a temporary dict you could use a dict comprehension instead, example:



                  def where(self, cond):
                  return type(self)({key: value for key, value in self.json.items() if cond(key, value)})


                  In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.



                  print seems like an unnecessary function, but if you keep it the return lines have no effect.



                  Hope that's helpful.






                  share|improve this answer








                  New contributor



                  bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  $endgroup$



                  A few notes:



                  Firstly I would add some docstrings to each function to document what the expected behaviour is.



                  In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy?



                  In select, where, astype instead of creating a temporary dict you could use a dict comprehension instead, example:



                  def where(self, cond):
                  return type(self)({key: value for key, value in self.json.items() if cond(key, value)})


                  In astype you're using JSONSelector, however everywhere else you're using type(self) this should be consistent whichever one you go for.



                  print seems like an unnecessary function, but if you keep it the return lines have no effect.



                  Hope that's helpful.







                  share|improve this answer








                  New contributor



                  bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  share|improve this answer



                  share|improve this answer






                  New contributor



                  bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  answered 7 hours ago









                  bertilnilssonbertilnilsson

                  311




                  311




                  New contributor



                  bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.




                  New contributor




                  bertilnilsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.



























                      2












                      $begingroup$

                      Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.



                      Something closer to:



                      def foreach(self, func):
                      for key, value in self.json.items():
                      should_continue = func(key, value)

                      if should_continue == False:
                      break


                      If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:



                      def foreach(self, func):
                      for key, value in self.json.items():
                      should_break = func(key, value)

                      if should_continue:
                      break




                      I'm not sure there's much benefit to using your print method. I believe it's convoluting the simple task of just passing the object to print. If the user wants to pass some function before printing, just let them do it.



                      As an example, what intuitively makes more sense to you?:



                      json.print(str)


                      or



                      print(str(json))


                      Personally, I find the latter to make more sense.



                      I'll also note, your returns in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit return happens at the end of the method anyway.



                      Finally, I don't think negating the condition in if not func helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:



                      def print(self, func = None):
                      if func:
                      print(func(self))

                      else:
                      print(self)





                      share|improve this answer











                      $endgroup$


















                        2












                        $begingroup$

                        Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.



                        Something closer to:



                        def foreach(self, func):
                        for key, value in self.json.items():
                        should_continue = func(key, value)

                        if should_continue == False:
                        break


                        If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:



                        def foreach(self, func):
                        for key, value in self.json.items():
                        should_break = func(key, value)

                        if should_continue:
                        break




                        I'm not sure there's much benefit to using your print method. I believe it's convoluting the simple task of just passing the object to print. If the user wants to pass some function before printing, just let them do it.



                        As an example, what intuitively makes more sense to you?:



                        json.print(str)


                        or



                        print(str(json))


                        Personally, I find the latter to make more sense.



                        I'll also note, your returns in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit return happens at the end of the method anyway.



                        Finally, I don't think negating the condition in if not func helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:



                        def print(self, func = None):
                        if func:
                        print(func(self))

                        else:
                        print(self)





                        share|improve this answer











                        $endgroup$
















                          2












                          2








                          2





                          $begingroup$

                          Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.



                          Something closer to:



                          def foreach(self, func):
                          for key, value in self.json.items():
                          should_continue = func(key, value)

                          if should_continue == False:
                          break


                          If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:



                          def foreach(self, func):
                          for key, value in self.json.items():
                          should_break = func(key, value)

                          if should_continue:
                          break




                          I'm not sure there's much benefit to using your print method. I believe it's convoluting the simple task of just passing the object to print. If the user wants to pass some function before printing, just let them do it.



                          As an example, what intuitively makes more sense to you?:



                          json.print(str)


                          or



                          print(str(json))


                          Personally, I find the latter to make more sense.



                          I'll also note, your returns in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit return happens at the end of the method anyway.



                          Finally, I don't think negating the condition in if not func helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:



                          def print(self, func = None):
                          if func:
                          print(func(self))

                          else:
                          print(self)





                          share|improve this answer











                          $endgroup$



                          Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.



                          Something closer to:



                          def foreach(self, func):
                          for key, value in self.json.items():
                          should_continue = func(key, value)

                          if should_continue == False:
                          break


                          If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:



                          def foreach(self, func):
                          for key, value in self.json.items():
                          should_break = func(key, value)

                          if should_continue:
                          break




                          I'm not sure there's much benefit to using your print method. I believe it's convoluting the simple task of just passing the object to print. If the user wants to pass some function before printing, just let them do it.



                          As an example, what intuitively makes more sense to you?:



                          json.print(str)


                          or



                          print(str(json))


                          Personally, I find the latter to make more sense.



                          I'll also note, your returns in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit return happens at the end of the method anyway.



                          Finally, I don't think negating the condition in if not func helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:



                          def print(self, func = None):
                          if func:
                          print(func(self))

                          else:
                          print(self)






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 4 hours ago

























                          answered 6 hours ago









                          CarcigenicateCarcigenicate

                          5,33611737




                          5,33611737






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • 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.


                              Use MathJax to format equations. MathJax reference.


                              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%2fcodereview.stackexchange.com%2fquestions%2f222597%2fjson-selector-class-in-python%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

                              Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                              Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                              Ciclooctatetraenă Vezi și | Bibliografie | Meniu de navigare637866text4148569-500570979m