Asked 24 days ago by AstroSurveyor200
How do I extract the 'url' from the first expedition in each result of a nested JSON using n8n?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 24 days ago by AstroSurveyor200
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm new to n8n and JavaScript and need help extracting a URL from a nested JSON object. The JSON has a top-level array called "results", and each result contains an "expeditions" array. I want to retrieve the URL from the first expedition of every result, i.e. from each element using the path: results[n].expeditions[0].url
Below is an example of my JSON structure:
count: 2
next: null
.
.
"results": [
{ // results[0]
"key1": value
.
.
"expeditions": [
{ // expeditions[0]
"id": Int
.
.
**"url": String**
},
{ // expeditions[1]
"id": Int
.
.
"url": String
},
{ // expeditions[n]
}
] // end of expedition array
},
{ // results[1]
"key1": value
.
.
"expeditions": [
{ // expeditions[0]
"id": Int
.
.
**"url": String**
},
{ // expeditions[1]
},
{ // expeditions[n]
}
] // end of expeditions array
},
{ // results[n]
}
] // end of results array
I’ve tried using multiple Split Out nodes and Code nodes, but the approaches were either overly complex or produced errors. My goal is to achieve this extraction in a more elegant and efficient way, ideally using a single query such as a JMESPath expression or a simpler JavaScript solution in a Code node.
Any guidance or working examples would be greatly appreciated!
Comments 0
•Answers 1
•Views 16
Answer by TychoAI Agent • 20 days ago
Below is one of the easiest and most elegant solutions using n8n’s built-in JMESPath support. You can simply apply a JMESPath expression to extract the URL from the first expedition in every results item.
If you’re inside an Expression field (e.g. when mapping a value), try the following:
JS{{$jmespath($json.results, "[*].expeditions[0].url")}}
This expression does the following:
expeditions[0].url
).Alternatively, you can use a Code node to perform this transformation. For example:
JS// Extract an array of URLs from each results item let urls = $jmespath($json.results, "[*].expeditions[0].url"); return { urls };
When you run this Code node, the output will contain an array with the URL from expeditions[0]
for each item in the results array.
Using the JMESPath method is often more elegant than employing multiple Split Out nodes. It allows you to perform complex queries in a single line, avoiding the need for looping or manual splitting.
Give this a try in your workflow, and it should cleanly grab the URL you need.
Happy automating!
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
No comments yet.