Using JSON $item order and suppressing "No data found..."

Hello! I have a returned .JSON which looks like this and is actually in a set order:

        "civilization": "Britons"
        "civilization": "Celts"

And I’m trying to use the variables further on down the line with $item("x"), except i’m struggling with errors as javascript is looking for data at indexes which don’t exist. They sometimes do, but sometimes they don’t, depending on the starting JSON, which changes every time. For instance in my example above there’s no 3rd entry, so using


You’d get:

[No data found for item-index: "2"]

I have tried using a nullish operator
{{ $item("2").$node["CivList"].json["civilization"] ?? "I am undefined!" }}
to suppress the error, but unfortunately n8n doesn’t like it when using item

Does anybody have any ideas on what I can do instead?

Many thanks!

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:

@UnluckyForSome , it is not quite clear to me if the index 2 is constant in your use case. If it is, then you can check if it exists first. For example,

const arr = [
      "civilization": "Britons"
      "civilization": "Celts"

const item = arr.length > 2 ? arr[2].civilization : null;

Here, if index 2 exist (more than 2 items in the list) you can safely reference that index. Otherwise the value will be null and no error accessing non-existent item.

Hi @ihortom, thankyou for your help!

I’m getting close but still not quite there.

See here, I want to be able to reference item 273 in a future node. Most of the time it doens’t exist (in this example there are only 2 records not 273)

So in this instance I want to return “does not exist…” but the code errors out instead of returning

P.S there must be a better way of referencing the JSON output of a node, I used $input.all(); here in my example but I need to be more specific taking this to my actual workflow.

Sorry I know this is basic javascript :frowning:

Kind regards,

@UnluckyForSome , I can see 2 problems in your JS code:

  1. Items are still not addressed correctly (my example was generic for JS but n8n has more complex structure then it shows it in the UI)
  2. Returned value is not in expected format

To fix, your JS code in Code node should look like this

const items = $input.all().map(i => i.json);

civiliz = items[273] ? items[273] : {civilization: "does not exist but we still return me anyway!"};

return civiliz;
1 Like