Python Code Node Issue: Assigning List to JSON Field Fails (`_input.all()[0]`)

Describe the problem/error/question

I’m working with Python in the Code node of n8n, and I’m encountering an issue when trying to assign a list of dictionaries to _input.all()[0].json["content_list"] = content_list. The result ends up as _input.all()[0].json["content_list"] = None. However, when I use an intermediary line to turn the object into a string (i.e., content_list = json.dumps(content_list)), the assignment works as expected.

However, I do not want it as a string, but keep it an n8n native object.
I looked in the docs, but I am unsure how to format the list properly so that I can assign it to the json field correctly.

Please share your workflow

    {
      "parameters": {
        "language": "python",
        "pythonCode": 
""""
import json
content_list = []

for entry in _input.first().json["data"]:
    content_value = entry.pop("content", None)
    if content_value is not None:
        content_list.append({"content": content_value})

# content_list = json.dumps(content_list)

_input.all()[0].json["content_list"] = content_list
return _input.all()

"""
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        720
      ],
      "id": "a2711ecf-efb2-4d26-8d7b-aa5a47adedf7",
      "name": "Code1"
    },

This ‘json’ there is really not pythonic :confused:

Work-around
+1 Fix-node (added behind the the above node with python code, enabled content_list = json.dumps(content_list):

The new node:
Node: Edit Fields1
Mode: Manual Mapping
Add fields/Fields to Set: content_list (Array)
= {{ JSON.parse($json.content_list) }}

# ##
That’s it.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.