n8n Python Snippet

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.


Published: November 9, 2025
Updated: November 30, 2025

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.

  1. Read a field from the previous node
return {"newKey": item["json"]["oldKey"]}
  1. Add a static constant
return {"status": "paid", "source": "n8n"}
  1. UTC timestamp as an ISO string
import datetime
return {"ts": datetime.datetime.utcnow().isoformat()}
  1. Trim/slice a string
return {"short": item["json"]["orderId"][-6:]}
  1. Remove new-lines or extra spaces
return {"clean": item["json"]["title"].replace("\n", " ")}
  1. Normalise case
return {"email": item["json"]["mail"].lower()}
  1. Quick if/else tag
amt = item["json"]["amount"]
return {"tag": "VIP" if amt > 1000 else "Normal"}
  1. Filter a list in one line
ok = [x for x in item["json"]["lines"] if x["status"] == "ok"]
return {"okLines": ok}
  1. Sum values inside an array
total = sum(float(l["price"]) for l in item["json"]["lines"])
return {"total": total}
  1. 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}
  1. Build a friendly sentence
return {"text": f'{item["json"]["name"]} 的订单 {item["json"]["id"]} 已发货'}
  1. Random coupon code (8 chars)
import secrets, string
alphabet = string.ascii_uppercase + string.digits
return {"code": ''.join(secrets.choice(alphabet) for _ in range(8))}
  1. Base64 encode for Basic auth
import base64
return {"b64": base64.b64encode(item["json"]["text"].encode()).decode()}
  1. JSON → string (pretty log)
import json
return {"str": json.dumps(item["json"], ensure_ascii=False)}
  1. String → JSON (parse raw body)
import json
return json.loads(item["json"]["raw"])
  1. Fire a quick POST (no HTTP node)
import requests
r = requests.post("https://api.x.com", json=item["json"], timeout=10)
return r.json()
  1. Grab an environment variable
import os
return {"token": os.getenv("API_TOKEN")}
  1. 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()}
  1. Rate-limiting pause (0.3 s)
import time
time.sleep(0.3)
return item["json"]
  1. Halt workflow on bad data
if not item["json"].get("email"):
    raise ValueError("email missing")

Tips

  • Whatever you return become is the new item.json for the next node.
  • Need heavy libs (pandas, numpy)? Install them first via Settings → Community nodes or a Execute Command node:
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!

Leave a Reply

Your email address will not be published. Required fields are marked *