Back to Catalog

JSON data utility: extract key-value pairs by index

WeblineIndiaWeblineIndia
153 views
2/3/2026
Official Page

Extract a key–value pair by index from JSON to fields in n8n

This template takes a JSON object and a row index and returns exactly one key–value pair at that index. It’s a handy helper when you only need a single entry from a structured JSON payload (e.g., picking one form field for downstream logic).

Who’s it for

  • Makers who want a quick JSON picker without writing full parsing logic.
  • Developers testing API payloads or building proofs of concept.
  • Ops/analysts who need to pluck a single field for emails, documents or notifications.

How it works

  1. Manual Trigger (When clicking ‘Test workflow’) starts the flow.
  2. Set → Input JSON Node holds your sample payload with:
    • myData: an object of key → value pairs.
    • rowIndex: a 0‑based index indicating which pair to extract.
  3. Code (Python) → Find Key‑Value Pair iterates myData and returns [key, value] at rowIndex as result.
  4. Set → Key maps result[0] to a field named result.
  5. Set → Value maps result[1] to a field named result[1].
  6. The selected key and value are then available to any downstream nodes.

How to set up

  1. Open the workflow and select Input JSON Node.
  2. Replace the sample with your own JSON:
    {
      "myData": { "name": "Alice", "age": "30", "city": "Paris" },
      "rowIndex": "1"
    }
    
  3. Click Execute Workflow. Check the Key and Value nodes for the outputs.

Requirements

  • n8n running (cloud or self‑hosted).
  • Code node (Python) enabled in your n8n version.
  • Input payload structure:
    • myData: object with keys/values
    • rowIndex: integer (0‑based)

How to customize

  • Pick by key name (instead of index): adjust the Python code to look up a specific key.
  • Handle nested objects/arrays: walk or flatten the structure before selecting.
  • Change output shape: return { "key": ..., "value": ... } or write directly to next‑node fields.
  • Validate inputs: add checks for out‑of‑range rowIndex, non‑object myData, or empty objects.

Add‑ons

  • Webhook intake: Replace Manual Trigger with a Webhook to accept live JSON.
  • Schema guard: Add an If/Function step to ensure myData is an object and rowIndex is numeric.
  • Audit log: Append the selected key/value to Google Sheets or a database.

Use Case Examples

  • Pull one field from a large API response to include in an email.
  • Extract a specific answer from a form submission for conditional routing.
  • Read a configuration pair from a settings object to control a downstream step.

Common troubleshooting

| Issue | Possible Cause | Solution | |---|---|---| | “Index out of range” | rowIndex is larger than the number of keys | Use a valid 0‑based index; add a guard in the Code node to clamp or default. | | Wrong key returned | Object key order differs from expectations | Object key order isn’t guaranteed across sources—prefer pick by key name for reliability. | | Empty/invalid output | myData is not an object or is empty | Ensure myData is a flat object with at least one key. | | Python errors | Code node’s Python runtime not available | Enable Python in the Code node or convert the snippet to JavaScript. | | Value type mismatch | Value isn’t a string | Cast as needed in the Set node or normalize types in the Code node. |

Need Help?

If you’d like this to pick by key, handle nested JSON, accept data via Webhook or fully customized to your needs, write to us and we’ll adapt the template to your exact use case.

n8n JSON Data Utility: Extract Key-Value Pairs by Index

This n8n workflow provides a robust utility for extracting specific key-value pairs from JSON data based on their index. It's particularly useful for processing structured data where you need to isolate particular elements or attributes for further use.

What it does

This workflow is designed to demonstrate and facilitate the extraction of data from a JSON object using JavaScript within a Code node.

  1. Manual Trigger: The workflow starts with a manual trigger, allowing you to execute it on demand.
  2. Edit Fields (Set): This node initializes a sample JSON data structure. This is where you would typically input or receive your JSON data that you want to process.
  3. Code: This is the core of the workflow. It uses JavaScript to iterate through the items provided by the previous node and extracts specific key-value pairs based on their index within the json array. The extracted data is then added to the output.

Prerequisites/Requirements

  • An n8n instance (cloud or self-hosted).
  • Basic understanding of JSON data structures and JavaScript array indexing.

Setup/Usage

  1. Import the workflow:
    • Copy the provided JSON workflow definition.
    • In your n8n instance, click "New" to create a new workflow.
    • Go to the "Workflows" menu, click "Import from JSON", and paste the copied JSON.
  2. Configure the "Edit Fields (Set)" node:
    • By default, this node contains sample JSON data. You can modify the json array within this node to match the structure of the data you wish to process.
    • Ensure your input data is an array of objects if you intend to use the indexing logic in the "Code" node as-is.
  3. Configure the "Code" node:
    • The JavaScript code is pre-configured to extract specific fields. Review the code to understand how it accesses item.json.json[index].key and item.json.json[index].value.
    • Adjust the index and the key/value paths if your input JSON structure differs or if you want to extract different fields.
  4. Execute the workflow:
    • Click the "Execute Workflow" button on the "Manual Trigger" node to run the workflow and see the output.

This workflow serves as an excellent starting point for anyone looking to programmatically extract and manipulate specific data points from complex JSON structures within n8n.

Related Templates

Two-way property repair management system with Google Sheets & Drive

This workflow automates the repair request process between tenants and building managers, keeping all updates organized in a single spreadsheet. It is composed of two coordinated workflows, as two separate triggers are required — one for new repair submissions and another for repair updates. A Unique Unit ID that corresponds to individual units is attributed to each request, and timestamps are used to coordinate repair updates with specific requests. General use cases include: Property managers who manage multiple buildings or units. Building owners looking to centralize tenant repair communication. Automation builders who want to learn multi-trigger workflow design in n8n. --- ⚙️ How It Works Workflow 1 – New Repair Requests Behind the Scenes: A tenant fills out a Google Form (“Repair Request Form”), which automatically adds a new row to a linked Google Sheet. Steps: Trigger: Google Sheets rowAdded – runs when a new form entry appears. Extract & Format: Collects all relevant form data (address, unit, urgency, contacts). Generate Unit ID: Creates a standardized identifier (e.g., BUILDING-UNIT) for tracking. Email Notification: Sends the building manager a formatted email summarizing the repair details and including a link to a Repair Update Form (which activates Workflow 2). --- Workflow 2 – Repair Updates Behind the Scenes:\ Triggered when the building manager submits a follow-up form (“Repair Update Form”). Steps: Lookup by UUID: Uses the Unit ID from Workflow 1 to find the existing row in the Google Sheet. Conditional Logic: If photos are uploaded: Saves each image to a Google Drive folder, renames files consistently, and adds URLs to the sheet. If no photos: Skips the upload step and processes textual updates only. Merge & Update: Combines new data with existing repair info in the same spreadsheet row — enabling a full repair history in one place. --- 🧩 Requirements Google Account (for Forms, Sheets, and Drive) Gmail/email node connected for sending notifications n8n credentials configured for Google API access --- ⚡ Setup Instructions (see more detail in workflow) Import both workflows into n8n, then copy one into a second workflow. Change manual trigger in workflow 2 to a n8n Form node. Connect Google credentials to all nodes. Update spreadsheet and folder IDs in the corresponding nodes. Customize email text, sender name, and form links for your organization. Test each workflow with a sample repair request and a repair update submission. --- 🛠️ Customization Ideas Add Slack or Telegram notifications for urgent repairs. Auto-create folders per building or unit for photo uploads. Generate monthly repair summaries using Google Sheets triggers. Add an AI node to create summaries/extract relevant repair data from repair request that include long submissions.

Matt@VeraisonLabsBy Matt@VeraisonLabs
208

Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation

PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive ➜ Download PDF ➜ OCR text ➜ AI normalize to JSON ➜ Upsert Buyer (Account) ➜ Create Opportunity ➜ Map Products ➜ Create OLI via Composite API ➜ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content → the parsed JSON (ensure it’s an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id ➜ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total ➜ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger → Download File From Google Download File From Google → Extract from File → Update File to One Drive Extract from File → Message a model Message a model → Create or update an account Create or update an account → Create an opportunity Create an opportunity → Build SOQL Build SOQL → Query PricebookEntries Query PricebookEntries → Code in JavaScript Code in JavaScript → Create Opportunity Line Items --- Quick setup checklist 🔐 Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. 📂 IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) 🧠 AI Prompt: Use the strict system prompt; jsonOutput = true. 🧾 Field mappings: Buyer tax id/name → Account upsert fields Invoice code/date/amount → Opportunity fields Product name must equal your Product2.ProductCode in SF. ✅ Test: Drop a sample PDF → verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep “Return only a JSON array” as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields don’t support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your org’s domain or use the Salesforce node’s Bulk Upsert for simplicity.

Le NguyenBy Le Nguyen
942

AI-powered code review with linting, red-marked corrections in Google Sheets & Slack

Advanced Code Review Automation (AI + Lint + Slack) Who’s it for For software engineers, QA teams, and tech leads who want to automate intelligent code reviews with both AI-driven suggestions and rule-based linting — all managed in Google Sheets with instant Slack summaries. How it works This workflow performs a two-layer review system: Lint Check: Runs a lightweight static analysis to find common issues (e.g., use of var, console.log, unbalanced braces). AI Review: Sends valid code to Gemini AI, which provides human-like review feedback with severity classification (Critical, Major, Minor) and visual highlights (red/orange tags). Formatter: Combines lint and AI results, calculating an overall score (0–10). Aggregator: Summarizes results for quick comparison. Google Sheets Writer: Appends results to your review log. Slack Notification: Posts a concise summary (e.g., number of issues and average score) to your team’s channel. How to set up Connect Google Sheets and Slack credentials in n8n. Replace placeholders (<YOURSPREADSHEETID>, <YOURSHEETGIDORNAME>, <YOURSLACKCHANNEL_ID>). Adjust the AI review prompt or lint rules as needed. Activate the workflow — reviews will start automatically whenever new code is added to the sheet. Requirements Google Sheets and Slack integrations enabled A configured AI node (Gemini, OpenAI, or compatible) Proper permissions to write to your target Google Sheet How to customize Add more linting rules (naming conventions, spacing, forbidden APIs) Extend the AI prompt for project-specific guidelines Customize the Slack message formatting Export analytics to a dashboard (e.g., Notion or Data Studio) Why it’s valuable This workflow brings realistic, team-oriented AI-assisted code review to n8n — combining the speed of automated linting with the nuance of human-style feedback. It saves time, improves code quality, and keeps your team’s review history transparent and centralized.

higashiyama By higashiyama
90