Background is I'm getting data from a JSON API where lots of fields are optional and I want most of the fields in a database. When a specific field isn't available I want an empty string (""
) written into the database.
Currently I've been doing:
if jsonobject.what_i_look_for:
dbstring = jsonobject.what_i_look_for
else:
dbstring = ""
And then inserted dbstring into the database. However I'm getting a lot more of these fields now and I want a much cleaner code rather than a function which consists about 80% of if-statements.
I've found if-shorthands and this shorthand to check if a variable is empty, but both don't seem to work directly as a string. I've tested this using print()
in an interactive python 3.5.2 shell:
>>> print(testvar or "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
>>> print(testvar if testvar else "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
This: echo (isset($testvar) ? $testvar : "");
is the PHP equivalent of what I seek.
Edit: Since it seems relevant: The object I am trying to process is coming from Telegram's JSON API. I'm using python-telegram-bot
as library and this is an example object.