Whilst figuring out how the Code node works and behaves, I worked out a few samples that might help others getting started with this node. The Code node is extremely powerful, but not always easy to understand (at first). Also, the documentation is not always completely/up-to-date, and the error messages aren’t always very helpful, at least to simple mortals like myself
First, it’s essential that you have a basic understanding of the JSON structure, especially the difference between and Object and an Array.
An example of an Object … 1 item:
{
"color": "red",
"value": "#f00"
}
And example of an Array … 1 or (generally) more items:
[
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
},
{
"color": "blue",
"value": "#00f"
}
]
The samples I worked out:
NOTE: the output (display) of on Object is [{}] which suggest it’s an array, but it is actually an object {}
When starting with the Code node, you have to specify the mode in which you want it to operate. You’ve got two choices:
- Run Once for All Items … see examples Get Array from Object & Delete Keys For Loop
- Run Once for Each Item … see example Change Structure via Code Node
NOTE: use $input.all()[0].json. to get to the JSON data.
NOTE: if you’re using the JMESPath query (https://jmespath.org) to remove the “” around the key. So [].{“firstName”: first} in JMESPath needs to be [].{firstName: first} in n8n … both the in the Code and Set node
JSON Tools: https://jsonlint.com, https://jsonpathfinder.com, https://jsoneditoronline.org
Dummy data: dummyjson.com