How to access first element of the list

Describe the problem/error/question

I’m trying to access nested objects in my workflow data, but my code isn’t properly accessing the nested data structure.

What is the error message (if any)?

My validation code isn’t accessing the nested objects correctly. It’s trying to validate fields directly at the top level, but the data structure has additional nesting.

Please share your workflow

C0Ahkz3TxVnckO9B

Share the output returned by the last node

The output data structure I’m trying to process is:

[
   {
      "data":[
         {
            "Name":"John Doe",
            "address":"123 Main St, New York, NY",
            "courses":[
               "Maths",
               "Computer"
            ]
         },
         {
            "Name":"Jane Smith",
            "address":"456 Elm St, Los Angeles, CA",
            "courses":[
               "Physics",
               "Chemistry"
            ]
         }
      ]
   }
]

Hi,

what you have is an array which you access like {{ $json.data[0] }}
if you want items that can be processed individually each would need to have its own key… please refer to Understanding the data structure | n8n Docs

One other option is to use Splitout node that effectively extracts a nested array and allows treating items as if they were directly produced by some node in a standard n8n way.

This is my code:

data_list = _input.all()


# Extract the single object inside the list
if data_list:
  data = data_list[0]
      top_level_fields = ["Name", "address", "courses"]
    for key in top_level_fields:
        if key not in data[0] or data[0][key] in [None, ""]:
            invalid_fields[key] = "Empty or invalid"

    # Check courses fields
    if "courses" in data[0] and isinstance(data[0]["courses"], list):
        for index, course in enumerate(data[0]["courses"], start=1):
            if course in [None, ""]:
                invalid_fields.setdefault("courses", {})[f"course{index}"] = "Empty or invalid"
    else:
        invalid_fields["courses"] = "Must be a non-empty list"

# Final return statement
if invalid_fields:
    result = {"invalid_fields": invalid_fields}
else:
    result = {"message": "successful"}
return result

  • Now when I’m accessing this list using data = data[0]. it’s not working as expected, as data should be equal to now the object( look at above payload, since I’m using loop so one object will go in the loop)

output I’m getting is this:

[
{
"invalid_fields": 
{
"Name": 
"Empty or invalid",
"address": 
"Empty or invalid",
"courses": 
"Must be a non-empty list"
}
}
]

Each item from the _input has some extra fields where actual data is stored. You need to look into json property to find the fields you’re looking for. The other one is binary and a few others that carry all the n8n data magic within n8n.

@jcuypers shared a link to a very insightful document reading which would help you to prevent this pitfall and do less of guesswork.

i agree with the splitout tbh, at least you could use the no-code options to its fullest. now he’s writing code where there shouldn’t be.

could you suggest the workflow, How would you implement it, Now if I don’t use this code see how many nodes I would need to use… so it would be nice if you show me dummy workflow of above scenario.

could you access my workflow through workflow Id and make necessary changes? this would be very helpful to me…

You need to decide on your priorities - js code or possibly more of no-code nodes. No-code comes at a cost.

Not possible.

You could post your workflow here using the </> button.

Main goal here is to validate this payload:

{
  "data": [
    {
      "Name": "John Doe",
      "address": {
        "address_line": "123 Main St",
        "city": "New York",
        "state": "NY"
      },
      "courses": ["Maths", "Computer"]
    },
    {
      "Name": "Jane Smith",
      "address": {
        "address_line": "456 Elm St",
        "city": "Los Angeles",
        "state": "CA"
      },
      "courses": ["Physics", "Chemistry"]
    }
  ]
}

  • validate all key- values, subkeys and their values and all.
  • which means validate address_line, city, state, etc
  • for validation just check if they are empty or not and save them into a dictionary.
  • actual payload is much complex let me share, in which I have to validate all things. look at it:

this is actual payload:

[
  {
    "agency_id": "",
    "agency": "Himanshu-Academy",
    "tellus_user_id": "",
    "tellus_password": "pass123",
    "payer_type": "Medicaid",
    "program": {
      "program_name": "Home Care",
      "medicaid_id": "",
      "unit_multiplier": 1.5
    },
    "call_type": {
      "procedure_code": "PROC100",
      "call_type_name": "In-Home Visit"
    },
    "client": [
      {
        "client_id": "12",
        "medicaid_id": 101,
        "dob": "2002-02-03",
        "ssn": "",
        "gender": "Male",
        "address": {
          "address": "123 Main St",
          "address_line": "Apt 4B",
          "city": "Miami",
          "state": "FL",
          "zip": ""
        },
        "diagnosis": "code10"
      },
      {
        "client_id": "13",
        "medicaid_id": 102,
        "dob": "",
        "ssn": "987-65-4321",
        "gender": "Female",
        "address": {
          "address": "456 Elm St",
          "address_line": "Suite 200",
          "city": "Orlando",
          "state": "FL",
          "zip": "32801"
        },
        "diagnosis": "code20"
      }
    ]
  }
]

Here is the replacement of your first Code node.

I am not fluent in pythonish but something is wrong with isinstance(data["courses"], list) there. Not much opportunities to see how n8n sends lists to python interpreter. I’d use type(data["courses"]) to see.

So, if I invested some effort into validating the schema of your initial example it would have gone in vain, right? Not very nice…
I think you are pretty capable of accomplishing this.
If you find any response (mine or @jcuypers’ ) above helpful, please mark it as a :white_check_mark: Solution.

I think schema validation is worth its own topic anyway. For the sake of future readers.

I did use type(data) but it doesn’t print output.

Just one question, Now what’s your opinion about using no-code options? what do you think will they work for this scenario. If they do, then please show me POC. @jcuypers. Scenario is simple to check if value (corresponding to a key) is empty or not. if empty put them into an invalid_fields object.

I wouldn’t go no-code to validate schema. Doesn’t make much sense, esp. if schema may vary. If schema doesn’t vary then no sense to accomodate for non-tech folks. If it does then they very likely won’t be able to handle changes anyway. It is not so much about coding but rather abount understanding data structures. A question to ask them: would you be able to express business data structure in any fomalized terms? And a question to you: would you be able to convert the description they provide into a JSON, yaml or whatever computer-readable format without asking for clarifications of any sort?

Was your initial question resolved? Seems like you are now able to access nested data structure.