Affiliate/Ads disclaimer: Some links on this blog are affiliate/ads links to support this project going on, meaning I may earn a commission at no extra cost to you.
n8n Python Snippet
Below is a concise, copy-paste-ready cheat sheet for the most frequently used Python snippets inside n8n.
Each bullet = one mini-recipe.
Drop the code straight into the Code → Python node and run.
- Read a field from the previous node
return {"newKey": item["json"]["oldKey"]}
- Add a static constant
return {"status": "paid", "source": "n8n"}
- UTC timestamp as an ISO string
import datetime
return {"ts": datetime.datetime.utcnow().isoformat()}
- Trim/slice a string
return {"short": item["json"]["orderId"][-6:]}
- Remove new-lines or extra spaces
return {"clean": item["json"]["title"].replace("\n", " ")}
- Normalise case
return {"email": item["json"]["mail"].lower()}
- Quick if/else tag
amt = item["json"]["amount"]
return {"tag": "VIP" if amt > 1000 else "Normal"}
- Filter a list in one line
ok = [x for x in item["json"]["lines"] if x["status"] == "ok"]
return {"okLines": ok}
- Sum values inside an array
total = sum(float(l["price"]) for l in item["json"]["lines"])
return {"total": total}
- Deduplicate by ID (keep 1st)
seen = set()
uniq = [x for x in item["json"]["list"]
if x["id"] not in seen and not seen.add(x["id"])]
return {"uniq": uniq}
- Build a friendly sentence
return {"text": f'{item["json"]["name"]} 的订单 {item["json"]["id"]} 已发货'}
- Random coupon code (8 chars)
import secrets, string
alphabet = string.ascii_uppercase + string.digits
return {"code": ''.join(secrets.choice(alphabet) for _ in range(8))}
- Base64 encode for Basic auth
import base64
return {"b64": base64.b64encode(item["json"]["text"].encode()).decode()}
- JSON → string (pretty log)
import json
return {"str": json.dumps(item["json"], ensure_ascii=False)}
- String → JSON (parse raw body)
import json return json.loads(item["json"]["raw"])
- Fire a quick POST (no HTTP node)
import requests
r = requests.post("https://api.x.com", json=item["json"], timeout=10)
return r.json()
- Grab an environment variable
import os
return {"token": os.getenv("API_TOKEN")}
- Single-row CSV export
import csv, io
o = io.StringIO()
w = csv.DictWriter(o, fieldnames=["id", "amount"])
w.writeheader()
w.writerow(item["json"])
return {"csv": o.getvalue()}
- Rate-limiting pause (0.3 s)
import time time.sleep(0.3) return item["json"]
- Halt workflow on bad data
if not item["json"].get("email"):
raise ValueError("email missing")
Tips
- Whatever you
returnbecome is the newitem.jsonfor the next node. - Need heavy libs (pandas, numpy)? Install them first via Settings → Community nodes or a
Execute Commandnode:
pip install pandas
- For snippets rated complex, consider wrapping them in a sub-workflow and calling them with Execute Workflow—it keeps the main flow tidy.
Happy automating!