I can't extract data from json by function

I have json data like this (by webhook):

I build function to extract “body” to text, and return, but see error:

Function (by function item):

const item = JSON.parse(item.body);
return item;

Error:

ERROR: Cannot access 'item' before initialization
    ReferenceError: Cannot access 'item' before initialization
        at /usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes:1:122
        at Object.<anonymous> (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes:2:14)
        at NodeVM.run (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/main.js:1121:29)
        at Object.executeSingle (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/FunctionItem.node.js:71:33)
        at Workflow.runNode (/usr/local/lib/node_modules/n8n/node_modules/n8n-workflow/dist/src/Workflow.js:565:60)
        at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/src/WorkflowExecute.js:369:62
        at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/src/WorkflowExecute.js:447:15
        at /usr/local/lib/node_modules/n8n/node_modules/p-cancelable/index.js:61:11
        at new Promise (<anonymous>)
        at new PCancelable (/usr/local/lib/node_modules/n8n/node_modules/p-cancelable/index.js:31:19)

Did you try giving the variable a different name? Like instead of item something like newItem so that you do not “overwrite” an already existing variable? So for example this:

const newItem = JSON.parse(item.body);
return newItem;

I still error:

```
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes:1:119
    at Object.<anonymous> (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes:3:2)
    at NodeVM.run (/usr/local/lib/node_modules/n8n/node_modules/vm2/lib/main.js:1121:29)
    at Object.executeSingle (/usr/local/lib/node_modules/n8n/node_modules/n8n-nodes-base/dist/nodes/FunctionItem.node.js:71:33)
    at Workflow.runNode (/usr/local/lib/node_modules/n8n/node_modules/n8n-workflow/dist/src/Workflow.js:565:60)
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/src/WorkflowExecute.js:369:62
    at /usr/local/lib/node_modules/n8n/node_modules/n8n-core/dist/src/WorkflowExecute.js:447:15
    at /usr/local/lib/node_modules/n8n/node_modules/p-cancelable/index.js:61:11
    at new Promise (<anonymous>)
```

Well, I don’t know why. But I’m successful with this code:

```
const newItem = JSON.parse(JSON.stringify(item.body));
return newItem;
```

Looking at the image you did post above is body already a JSON-Object. So there is no need for parsing at all. You can simply do:

const newItem = item.body;
return newItem;

or even simpler

return item.body
1 Like