How to get column names and values from Google Sheets in Python Code node n8n?

I need to loop through all the columns retrieved from Google Sheets and find out their names and values ​​through a code block like this:

data = _input.all()

for item in data:
    row = item["json"]

    for column_name, value in row.items():
        print(f"Столбец: {column_name}")
        print(f"Значение: {value}")

But I got an error saying _input doesn’t exist. So how do I loop through all the column names and their values?

Hi @Quent , welcome !

  1. _input is Python syntax. If you’re getting “_input doesn’t exist”, you’re likely in JavaScript mode. Check the Language dropdown at the top of the Code node. In JavaScript, the equivalent is $input.all().

  2. print() won’t show output. The Code node requires you to return items. print() output goes nowhere.

Here’s a working version in JavaScript (Run Once for All Items):

const results = [];
for (const item of $input.all()) {
  for (const [columnName, value] of Object.entries(item.json)) {
    results.push({ json: { columnName, value } });
  }
}
return results;

Or if you do switch to Python mode (requires Task Runners, enabled by default in 2.0+):

results = []
for item in _input.all():
    for column_name, value in item.json.items():
        results.append({"json": {"column_name": column_name, "value": value}})
return results

Let me know if it works :crossed_fingers:

Welcome @Quent to our community! I’m Jay and I am a n8n verified creator.

In n8n’s Python Code node, the variable is items (not _input). Each item in items is a dict with a json key. Here’s the corrected version:

for item in items:
    row = item["json"]
    for column_name, value in row.items():
        print(f"Column: {column_name}")
        print(f"Value: {value}")

return items

Note: you also need to return items at the end of the Code node or it will return nothing downstream.

That`s not works. Same error, only with items
Here my node settings:

That also doesn’t work. Same error

@Quent

Ok, the thing is, for Run Once For Each Item you have to use _item in singular, the For ALL Items mode you have to use _items.

so since you’re in Run Once For Each Item mode, try this :

row = _item[“json”]
for column_name, value in row.items():
print(f"Column: {column_name}“)
print(f"Value: {value}”)

return _item

That`s works! Thank you, @houda_ben