Null value causes error with .length() function

Using an HTTPS node, I get a string value called “cpf” that is normally 11 or 14 characters long. The number of characters indicate the type of customers: 11 chars is a person, 14 chars is a business.

The rest of the worflow depends on whether the customer is a person or a business, so I added an IF node, where I use the formula .length(). For exemple, using length(), “85342386004” is 11 chars (person), “14860895000193” is 14 chars (business) and i compare that value to 14.

The problem is that when the value of cpf is Null, the length function returns an error instead of returning zero:

Any sugestion to handle the null case?

{
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "2af8e9695dac61810dece2e50437238a531dcbceb4e16d344acd88c7ca0a986e"
  },
  "nodes": [
    {
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{ $('Split In Batches').item.json[\"cpf\"].length()}}",
              "operation": "equal",
              "value2": 14
            }
          ]
        }
      },
      "id": "2ca67bdc-81d4-4790-9c0d-0c3fe4a48cf0",
      "name": "IF Atacado",
      "type": "n8n-nodes-base.if",
      "position": [
        -1000,
        940
      ],
      "typeVersion": 1,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "content": "## Puxar dados do Kiskadi\n\nVerificar:\n- CNPJ\n- API creds no Kiskadi\n- \"transaction_last_minutes\": 15\n",
        "height": 386.8858833115132,
        "width": 355.36581843426404
      },
      "id": "1e7f1a14-800e-4534-a58d-e0ba4cefdb1f",
      "name": "Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1580,
        620
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{$json[\"DDD\"]}}",
              "operation": "larger",
              "value2": 28
            }
          ]
        }
      },
      "id": "15cbd262-695b-4b29-9f21-d35f1e6a02f9",
      "name": "Verificar DDD>28",
      "type": "n8n-nodes-base.if",
      "position": [
        -660,
        780
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "values": {
          "number": [
            {
              "name": "DDD",
              "value": "={{ $json[\"phone_number\"].toString().slice(0,2)}}"
            }
          ],
          "string": [
            {
              "name": "Quantidade numeros",
              "value": "={{ $json[\"phone_number\"].toString().length }}"
            },
            {
              "name": "tel_8leftmost",
              "value": "={{ $json[\"phone_number\"].toString().slice(-8) }}"
            }
          ]
        },
        "options": {}
      },
      "id": "48419d70-86da-4b19-adbc-69c2e7eaa0db",
      "name": "Count digits - extract 8leftmost",
      "type": "n8n-nodes-base.set",
      "position": [
        -840,
        780
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "fieldToSplitOut": "data",
        "options": {}
      },
      "id": "a5f88be7-ba3e-4086-82e9-6fac788f0363",
      "name": "Item Lists",
      "type": "n8n-nodes-base.itemLists",
      "position": [
        -1360,
        780
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "id": "de1479a0-072b-449c-b64d-af882877eba2",
      "name": "Split In Batches",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -1160,
        780
      ],
      "typeVersion": 2
    },
    {
      "parameters": {
        "amount": 30,
        "unit": "seconds"
      },
      "id": "24909cca-3b23-4cce-9ba6-8672d95d47de",
      "name": "Wait",
      "type": "n8n-nodes-base.wait",
      "position": [
        -80,
        760
      ],
      "webhookId": "db34da6b-fbd8-46cd-a46d-0b2ff6988d8f",
      "typeVersion": 1
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "whatsapp",
              "value": "=+55{{$json[\"DDD\"]}}{{$json[\"tel_8leftmost\"]}}"
            }
          ]
        },
        "options": {}
      },
      "id": "b600ed0e-1d21-4612-a996-d8823a79a4d5",
      "name": "Remove 9 & Add +55",
      "type": "n8n-nodes-base.set",
      "position": [
        -460,
        680
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "values": {
          "number": [
            {
              "name": "whatsapp",
              "value": "=+55{{ $json[\"phone_number\"] }}"
            }
          ]
        },
        "options": {}
      },
      "id": "0ccbc688-0dd5-4ad0-925c-380e6553d65e",
      "name": "ADD +55",
      "type": "n8n-nodes-base.set",
      "position": [
        -460,
        840
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "content": "copiado do\n\nhttps://n8n-vultr.kiskadi.com/workflow/LLuiPSsIkqJlh52e"
      },
      "id": "2e593dc5-c21f-4036-9395-e5a69a62dd4d",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1380,
        400
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://backend.botconversa.com.br/api/v1/webhooks-automation/catch/98047/peBq08Iyh0WE/",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "whatsapp",
              "value": "={{ $json[\"whatsapp\"] }}"
            },
            {
              "name": "nome",
              "value": "={{ $('Split In Batches').item.json[\"name\"] }}"
            },
            {
              "name": "k_saldo_cashback",
              "value": "={{ $('Split In Batches').item.json[\"total_currency_balance\"].toFloat().toFixed(2).replace(\".\" , \",\") }}"
            },
            {
              "name": "k_vendedor",
              "value": "={{ $('Split In Batches').item.json[\"salesperson_name\"].split(\" \")[0].toSentenceCase() }}"
            },
            {
              "name": "k_link_portal",
              "value": "={{ $('Split In Batches').item.json[\"registration_link\"] }}"
            },
            {
              "name": "k_nome_loja",
              "value": "={{ $json.branch_name }}"
            },
            {
              "name": "k_id_cliente",
              "value": "={{ $('Split In Batches').item.json[\"id\"] }}"
            },
            {
              "name": "k_vencimento_promo",
              "value": "={{ $today.plus({day:7}).toFormat('dd/MM/yyyy')}}"
            }
          ]
        },
        "options": {}
      },
      "id": "abae7ef1-2666-4c67-a4a1-f9c8bc4f2d2e",
      "name": "Webhook Sem vendas",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -260,
        760
      ],
      "retryOnFail": true,
      "typeVersion": 3,
      "credentials": {
        "httpHeaderAuth": {
          "id": "sF7cEcRRqlptWwFy",
          "name": "API-KEY-Botconversa-Atacado-Optico"
        }
      },
      "continueOnFail": true
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "90bd2d6f-7567-44be-9f35-a91888a0f4ea",
      "name": "Schedule daily 11h30",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1720,
        780
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "url": "https://api.kiskadi.com/api/v2/consumers/filter",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n\"last_purchase_date\": \"{{$today.minus({day:7})}}\",\n\"branch_cnpj\": \"17393408000173\" \n}",
        "options": {}
      },
      "id": "a24345c7-1f4f-48ed-aae6-f56e5b7262c1",
      "name": "GET sem vendas 90 dias",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -1520,
        780
      ],
      "retryOnFail": true,
      "typeVersion": 3,
      "credentials": {
        "httpBasicAuth": {
          "id": "BbLvbC6K1VPBH4pT",
          "name": "API Kiskadi - Atacado Optico"
        }
      }
    }
  ],
  "connections": {
    "IF Atacado": {
      "main": [
        [
          {
            "node": "Count digits - extract 8leftmost",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Split In Batches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificar DDD>28": {
      "main": [
        [
          {
            "node": "Remove 9 & Add +55",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "ADD +55",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Count digits - extract 8leftmost": {
      "main": [
        [
          {
            "node": "Verificar DDD>28",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Item Lists": {
      "main": [
        [
          {
            "node": "Split In Batches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split In Batches": {
      "main": [
        [
          {
            "node": "IF Atacado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait": {
      "main": [
        [
          {
            "node": "Split In Batches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remove 9 & Add +55": {
      "main": [
        [
          {
            "node": "Webhook Sem vendas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ADD +55": {
      "main": [
        [
          {
            "node": "Webhook Sem vendas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook Sem vendas": {
      "main": [
        [
          {
            "node": "Wait",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule daily 11h30": {
      "main": [
        [
          {
            "node": "GET sem vendas 90 dias",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET sem vendas 90 dias": {
      "main": [
        [
          {
            "node": "Item Lists",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {}
}```

## Share the output returned by the last node
<!-- If you need help with data transformations, please also share your expected output. -->

## Information on your n8n setup
- **n8n version:** 1.26.0
- **Database (default: SQLite):** sqlite
- **n8n EXECUTIONS_PROCESS setting (default: own, main):** main
- **Running n8n via (Docker, npm, n8n cloud, desktop app):**docker
- **Operating system:** linux

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

The problem is that you can’t call that function on an NULL object. A compact way to solve this is using a ternary expression: it checks if this property actually exists. If it does, it’ll return the string length - otherwise it’ll return zero.

2 Likes

@bartv has the right answer. Here is is so you can copy it
{{ $('Split In Batches').item.json["cpf"] ? $('Split In Batches').item.json["cpf"].length() : 0 }}

A ternary is just an if statement in one line. Whats the the left of the ? evaluates to a boolean (true or false). Null, 0, "", undefined are all examples of what would be evaluated as false.

If it evaluates true it will return what’s to the left of the : and to the right if it’s false

4 Likes

Awesome, I will try the ternary andreport back if it worked

You Can also do this:

$json.cpf?.length()

2 Likes

I tried {{ $(‘Split In Batches’).item.json[“cpf”]?.length()}} but it retirns undefined when the cpf field value is null

Yes but no error :slight_smile:
You can then put a “|| 0” to have a default value of 0 for example.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.