Elegant way to return json field if field is null in Python












1















I've a dumb question about my flask REST API. If i have a user model with a lot of information and i want to return it as json. But some of the information is still don't have any value (NULL). What's the elegant way to return it as a empty string or another default value instead of returning it as null.



Something like this:



{ 
'username': 'foo',
'fullname' : ''
}


instead of this:



{ 
'username': 'foo',
'fullname' : null
}


This is my function:



def json(self):
return {
'username': self.phone,
'fullname': self.fullname
}


This is the user model:



class UserModel(db.Model):
__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
fullname = db.Column(db.String(80))









share|improve this question

























  • can you post your nominal User model structure (definition)?

    – RomanPerekhrest
    Jan 19 at 9:15













  • @RomanPerekhrest i've edited my post

    – ikhsan
    Jan 19 at 9:17
















1















I've a dumb question about my flask REST API. If i have a user model with a lot of information and i want to return it as json. But some of the information is still don't have any value (NULL). What's the elegant way to return it as a empty string or another default value instead of returning it as null.



Something like this:



{ 
'username': 'foo',
'fullname' : ''
}


instead of this:



{ 
'username': 'foo',
'fullname' : null
}


This is my function:



def json(self):
return {
'username': self.phone,
'fullname': self.fullname
}


This is the user model:



class UserModel(db.Model):
__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
fullname = db.Column(db.String(80))









share|improve this question

























  • can you post your nominal User model structure (definition)?

    – RomanPerekhrest
    Jan 19 at 9:15













  • @RomanPerekhrest i've edited my post

    – ikhsan
    Jan 19 at 9:17














1












1








1








I've a dumb question about my flask REST API. If i have a user model with a lot of information and i want to return it as json. But some of the information is still don't have any value (NULL). What's the elegant way to return it as a empty string or another default value instead of returning it as null.



Something like this:



{ 
'username': 'foo',
'fullname' : ''
}


instead of this:



{ 
'username': 'foo',
'fullname' : null
}


This is my function:



def json(self):
return {
'username': self.phone,
'fullname': self.fullname
}


This is the user model:



class UserModel(db.Model):
__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
fullname = db.Column(db.String(80))









share|improve this question
















I've a dumb question about my flask REST API. If i have a user model with a lot of information and i want to return it as json. But some of the information is still don't have any value (NULL). What's the elegant way to return it as a empty string or another default value instead of returning it as null.



Something like this:



{ 
'username': 'foo',
'fullname' : ''
}


instead of this:



{ 
'username': 'foo',
'fullname' : null
}


This is my function:



def json(self):
return {
'username': self.phone,
'fullname': self.fullname
}


This is the user model:



class UserModel(db.Model):
__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
fullname = db.Column(db.String(80))






python python-3.x rest flask






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 19 at 9:17







ikhsan

















asked Jan 19 at 9:13









ikhsanikhsan

795718




795718













  • can you post your nominal User model structure (definition)?

    – RomanPerekhrest
    Jan 19 at 9:15













  • @RomanPerekhrest i've edited my post

    – ikhsan
    Jan 19 at 9:17



















  • can you post your nominal User model structure (definition)?

    – RomanPerekhrest
    Jan 19 at 9:15













  • @RomanPerekhrest i've edited my post

    – ikhsan
    Jan 19 at 9:17

















can you post your nominal User model structure (definition)?

– RomanPerekhrest
Jan 19 at 9:15







can you post your nominal User model structure (definition)?

– RomanPerekhrest
Jan 19 at 9:15















@RomanPerekhrest i've edited my post

– ikhsan
Jan 19 at 9:17





@RomanPerekhrest i've edited my post

– ikhsan
Jan 19 at 9:17












3 Answers
3






active

oldest

votes


















3














sqlalchemy.schema.Column class allows specifying default= parameter:



class UserModel(db.Model):
__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
password = db.Column(db.String(80))
fullname = db.Column(db.String(80), default="")


https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default






share|improve this answer



















  • 1





    ah, great. thanks

    – ikhsan
    Jan 19 at 9:26











  • @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

    – DeepSpace
    Jan 19 at 9:27





















1














One way is to have conditions in your return dict:



def json(self):
return {
'username': self.phone if self.phone else '',
'fullname': self.fullname if self.fullname else ''
}





share|improve this answer

































    0














    Basically, if you want to override None value in Python, you can use or operator like this:



    def json(self):
    return {
    'username': self.phone,
    'fullname': self.fullname or 'some default value'
    }


    In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.



    Hope that helps.






    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%2f54265604%2felegant-way-to-return-json-field-if-field-is-null-in-python%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      sqlalchemy.schema.Column class allows specifying default= parameter:



      class UserModel(db.Model):
      __tablename__ = 'users'

      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(80))
      password = db.Column(db.String(80))
      fullname = db.Column(db.String(80), default="")


      https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default






      share|improve this answer



















      • 1





        ah, great. thanks

        – ikhsan
        Jan 19 at 9:26











      • @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

        – DeepSpace
        Jan 19 at 9:27


















      3














      sqlalchemy.schema.Column class allows specifying default= parameter:



      class UserModel(db.Model):
      __tablename__ = 'users'

      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(80))
      password = db.Column(db.String(80))
      fullname = db.Column(db.String(80), default="")


      https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default






      share|improve this answer



















      • 1





        ah, great. thanks

        – ikhsan
        Jan 19 at 9:26











      • @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

        – DeepSpace
        Jan 19 at 9:27
















      3












      3








      3







      sqlalchemy.schema.Column class allows specifying default= parameter:



      class UserModel(db.Model):
      __tablename__ = 'users'

      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(80))
      password = db.Column(db.String(80))
      fullname = db.Column(db.String(80), default="")


      https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default






      share|improve this answer













      sqlalchemy.schema.Column class allows specifying default= parameter:



      class UserModel(db.Model):
      __tablename__ = 'users'

      id = db.Column(db.Integer, primary_key=True)
      username = db.Column(db.String(80))
      password = db.Column(db.String(80))
      fullname = db.Column(db.String(80), default="")


      https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 19 at 9:24









      RomanPerekhrestRomanPerekhrest

      55.7k32253




      55.7k32253








      • 1





        ah, great. thanks

        – ikhsan
        Jan 19 at 9:26











      • @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

        – DeepSpace
        Jan 19 at 9:27
















      • 1





        ah, great. thanks

        – ikhsan
        Jan 19 at 9:26











      • @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

        – DeepSpace
        Jan 19 at 9:27










      1




      1





      ah, great. thanks

      – ikhsan
      Jan 19 at 9:26





      ah, great. thanks

      – ikhsan
      Jan 19 at 9:26













      @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

      – DeepSpace
      Jan 19 at 9:27







      @ikhsan I think you would want to set it to not-nullable otherwise None values may still present if assigned after initialization, and they will still be served by the API.

      – DeepSpace
      Jan 19 at 9:27















      1














      One way is to have conditions in your return dict:



      def json(self):
      return {
      'username': self.phone if self.phone else '',
      'fullname': self.fullname if self.fullname else ''
      }





      share|improve this answer






























        1














        One way is to have conditions in your return dict:



        def json(self):
        return {
        'username': self.phone if self.phone else '',
        'fullname': self.fullname if self.fullname else ''
        }





        share|improve this answer




























          1












          1








          1







          One way is to have conditions in your return dict:



          def json(self):
          return {
          'username': self.phone if self.phone else '',
          'fullname': self.fullname if self.fullname else ''
          }





          share|improve this answer















          One way is to have conditions in your return dict:



          def json(self):
          return {
          'username': self.phone if self.phone else '',
          'fullname': self.fullname if self.fullname else ''
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 19 at 9:22









          DeepSpace

          38.3k44470




          38.3k44470










          answered Jan 19 at 9:21









          SimonFSimonF

          1,540218




          1,540218























              0














              Basically, if you want to override None value in Python, you can use or operator like this:



              def json(self):
              return {
              'username': self.phone,
              'fullname': self.fullname or 'some default value'
              }


              In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.



              Hope that helps.






              share|improve this answer




























                0














                Basically, if you want to override None value in Python, you can use or operator like this:



                def json(self):
                return {
                'username': self.phone,
                'fullname': self.fullname or 'some default value'
                }


                In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.



                Hope that helps.






                share|improve this answer


























                  0












                  0








                  0







                  Basically, if you want to override None value in Python, you can use or operator like this:



                  def json(self):
                  return {
                  'username': self.phone,
                  'fullname': self.fullname or 'some default value'
                  }


                  In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.



                  Hope that helps.






                  share|improve this answer













                  Basically, if you want to override None value in Python, you can use or operator like this:



                  def json(self):
                  return {
                  'username': self.phone,
                  'fullname': self.fullname or 'some default value'
                  }


                  In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.



                  Hope that helps.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 19 at 9:27









                  Sergey ElkinSergey Elkin

                  562




                  562






























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54265604%2felegant-way-to-return-json-field-if-field-is-null-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