Python block handling empty portions of response


I'm new to Workflows (and pretty new to Python in general, so forgive me if this is a simple question). I am ingesting an API with some MDM device details, and then using that to upsert in to a PostgreSQL database.

For API responses where all of the fields have data, this works great. In some cases not all of the fields will have data, and as it stands the workflow just fails when that is the case. How would I add some logic to this block to just pass NULL through if there is no data in a specific field?

Here is the code block I have currently -

data =

return [{

Hi @Robby_Barnes ,

Your now assigning the to variable data, but then you're not using this variable, in the json, you're referencing to

You can conditionally add data like this using conditional assignments in both JS and Python.

With Python it would be best to assign the values to separate variables first, with something like this.

#Assign var
device_id = if != "" else null

#Use var in json
"device_id": device_id,

Using a JS block it would be as easy as:

#Directly in json
"device_id": {{ != "" ? null}},
1 Like

This is an interesting question! Did some testing as well and just want to add 2 cents: It looks like Python prefers None to null to denote empty values, and using ternaries to check for empty values looks to be tricky if any of the other objects in the path might be empty as well. This thread has some interesting ideas on implementing something like optional chaining in Python but all of them seem relatively wordy.

I'm wondering what your data looks like if some of the fields are missing @Robby_Barnes. I think, to Marc's point, that a JS block could work really well here, though you might want something like the following:

return [{
 /* ...etc */