JArray
iterate JArray
access JArray elements
JSON manipulation
programming tips

How to access elements of a JArray or iterate over them

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

JArray from Newtonsoft.Json is useful when you need flexible JSON traversal without creating a full typed model first. You can access elements by index, iterate with foreach, query nested values, or convert the array into strong types when the schema becomes stable.

Parse and Validate the JSON First

The safest starting point is to parse JSON into a JToken, then confirm that the token is actually an array. That avoids invalid casts when the payload shape changes.

csharp
1using System;
2using Newtonsoft.Json.Linq;
3
4string json = "[\"apple\", \"banana\", \"cherry\"]";
5JToken token = JToken.Parse(json);
6
7if (token is JArray array)
8{
9    Console.WriteLine($"Count: {array.Count}");
10}
11else
12{
13    Console.WriteLine("The payload is not an array.");
14}

If you already know the JSON root is an array, JArray.Parse is fine. If the source is less predictable, checking JToken first is more defensive.

Access Elements by Index

A JArray supports index access just like a list. This is the clearest option when you need one specific position.

csharp
1using System;
2using Newtonsoft.Json.Linq;
3
4JArray numbers = JArray.Parse("[10, 20, 30]");
5
6int first = numbers[0]!.Value<int>();
7int second = numbers[1]!.Value<int>();
8
9Console.WriteLine(first + second);

Use Value<T> when you want an explicit conversion to a target type. That makes the code easier to read than manually casting tokens everywhere.

Iterate Over Primitive Arrays

For arrays of strings, numbers, or booleans, foreach is usually the best approach.

csharp
1using System;
2using Newtonsoft.Json.Linq;
3
4JArray fruits = JArray.Parse("[\"apple\", \"banana\", \"cherry\"]");
5
6foreach (JToken item in fruits)
7{
8    Console.WriteLine(item.Value<string>());
9}

This keeps the traversal logic obvious and works well for logging, validation, and simple transformations.

Iterate Over Arrays of Objects

When the elements are JSON objects, treat each item as a JObject and read properties by name.

csharp
1using System;
2using Newtonsoft.Json.Linq;
3
4string usersJson = "[{\"id\":1,\"name\":\"Ana\"},{\"id\":2,\"name\":\"Ben\"}]";
5JArray users = JArray.Parse(usersJson);
6
7foreach (JObject user in users)
8{
9    int id = user.Value<int>("id");
10    string name = user.Value<string>("name") ?? "unknown";
11    Console.WriteLine($"{id}: {name}");
12}

This is a good fit when the JSON is dynamic or partially known and you do not want a typed DTO yet.

Real payloads are often deeper than one array. In that case, read the outer object first and then pull nested arrays by property name.

csharp
1using System;
2using Newtonsoft.Json.Linq;
3
4string payload = @"{
5  'orders': [
6    { 'id': 1, 'items': ['pen', 'book'] },
7    { 'id': 2, 'items': ['lamp'] }
8  ]
9}";
10
11JObject root = JObject.Parse(payload);
12JArray orders = (JArray?)root["orders"] ?? new JArray();
13
14foreach (JObject order in orders)
15{
16    int id = order.Value<int>("id");
17    JArray items = (JArray?)order["items"] ?? new JArray();
18    Console.WriteLine($"Order {id} has {items.Count} items.");
19}

This style is resilient because it gives you a natural place to handle missing or optional properties.

Convert to Strongly Typed Models When the Schema Stabilizes

JArray is convenient, but it should not replace typed models forever. Once the JSON structure is well defined, conversion to a List<T> usually makes downstream code simpler.

csharp
1using System;
2using System.Collections.Generic;
3using Newtonsoft.Json;
4
5public class UserDto
6{
7    public int Id { get; set; }
8    public string Name { get; set; } = string.Empty;
9}
10
11string jsonUsers = "[{\"Id\":1,\"Name\":\"Ana\"},{\"Id\":2,\"Name\":\"Ben\"}]";
12List<UserDto>? users = JsonConvert.DeserializeObject<List<UserDto>>(jsonUsers);
13
14Console.WriteLine(users?.Count ?? 0);

A useful rule is: use JArray for exploration and flexible handling, then move to typed classes once the contract is stable.

Common Pitfalls

One common mistake is assuming every element has the same shape and accessing properties without null checks. Another is casting straight to JArray without confirming the root token type first.

Index access can also fail when arrays are shorter than expected, so avoid hard-coded positions unless the format guarantees them. Finally, if the JSON is very large, loading the whole thing into a JArray may be wasteful. In those cases, a streaming JsonTextReader is a better fit.

Summary

  • Parse to JToken first when the payload shape may vary.
  • Use index access for direct element lookup and foreach for ordinary traversal.
  • Treat object arrays as sequences of JObject and read properties explicitly.
  • Handle nested arrays with null checks to avoid fragile code.
  • Convert to typed models once the JSON contract becomes stable.

Course illustration
Course illustration

All Rights Reserved.