How to add key if missing in json?

Hello,

I have a json looking like this:

[
   {
      "sku":"ABC123",
      "id":"123",
      "inventory":152
   },
   {
      "sku":"CDF456",
      "id":"456",
      "inventory":152
   },
   {
      "sku":"GHI789",
      "id":"789"
   }
]

I would like to add "inventory": 0 where it’s missing. How do I achieve that?

Thanks,
Martin

Hey @ericsonmartin,

Quick option would be to use a set node and for the inventory value use a Ternary operation so it would use the value of inventory if it exists and if not it uses a 0.

{{$json["inventory"] ? $json["inventory"] : 0}}

An example of this in a workflow is below.

Another option would be to use an if node to check if it is empty then use a set node to set the value and merge the outputs together like the example below.

Hopefully one of these will help :+1:

1 Like

Hi Jon,

You are awesome! This forum is awesome! n8n is awesome!

Thanks,
Martin

3 Likes