Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Answer from dguay on Stack Overflow
Discussions

How to print the Json Array using for each loop
Hi Guys, Below is my JsonResponse of type JsonArray and I want to iterate through this using for each loop. Can you please help if you have solved similar kind of problem? JsonResponse [{“predictions”:1,“confidences… More on forum.uipath.com
🌐 forum.uipath.com
4
1
January 19, 2022
java - JSON - Iterate through JSONArray - Stack Overflow
I have a JSON file with some arrays in it. I want to iterate through the file arrays and get their elements and their values. This is how my file looks like: { "JObjects": { "JAr... More on stackoverflow.com
🌐 stackoverflow.com
How to iterate this JSON Array using Java and org.json in Android? - Stack Overflow
This is as far as I got, I can't figure out how to loop through the individual items inside the second array. ... Either the JSON is wrong (same example as above), or it's not parsing it correctly? I've managed to solve the problem by doing a split on the string and put them each in their own ... More on stackoverflow.com
🌐 stackoverflow.com
Java loop over Json array? - Stack Overflow
This works fine for me, after typing what ntg posted, intellij let me know that this is possible. ... What library are you using? JsonElement is not in org.json.jar repo1.maven.org/maven2/org/json/json/20240303/json-20240303.jar ... I am presuming Gson.. Question tagging was bad. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Tabnine
tabnine.com › home page › code › java › javax.json.jsonarray
javax.json.JsonArray.forEach java code examples | Tabnine
/** * Returns a {@link Attributes} instance based on the given {@link JsonObject}. * * @param claims a json object with the claims to extract * @return an {@link Attributes} instance with attributes from the given json object */ public static Attributes toAttributes(JsonObject claims) { return claims.entrySet().stream().reduce(new MapAttributes(), (mapAttributes, entry) -> { String claimName = entry.getKey(); JsonValue claimValue = entry.getValue(); if (JsonValue.ValueType.ARRAY.equals(claimValue.getValueType())) { JsonArray jsonArray = claims.getJsonArray(claimName); jsonArray.forEach(arrayValue -> mapAttributes.addLast(claimName, asString(arrayValue))); } else { mapAttributes.addLast(claimName, asString(claimValue)); } return mapAttributes; }, (mapAttributes, mapAttributes2) -> mapAttributes); }
Top answer
1 of 6
102

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
2 of 6
23
for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

Find elsewhere
🌐
Baeldung
baeldung.com › home › json › iterating over an instance of org.json.jsonobject
Iterating Over an Instance of org.json.JSONObject | Baeldung
May 5, 2025 - In this tutorial, we’ll look at a couple of approaches for iterating over a JSONObject, a simple JSON representation for Java.
🌐
Example Code
example-code.com › java › json_array_iterate.asp
Java Iterate over JSON Array containing JSON Objects
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
Quora
quora.com › How-do-I-iterate-through-JSON-array-object
How to iterate through JSON array object - Quora
Answer (1 of 2): I have the below code which is currently giving me one result. I would like to iterate through the “comments” so that end result will returns all the comments. for each(comments in r.orderLines){ // get Collection comments webservice = webServiceFactory.createWebService('
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
Arrays in JSON are almost the same as arrays in JavaScript.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
JSONException - If there is no string value for the index. ... Determine if the value is null. ... Make a string from the contents of this JSONArray. The separator string is inserted between each element. Warning: This method assumes that the data structure is acyclical. ... JSONException - If the array contains an invalid number.
🌐
Android Developers
developer.android.com › api reference › jsonarray
JSONArray | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
🌐
Stack Overflow
stackoverflow.com › questions › 57626635 › how-do-i-get-every-json-elemet-in-a-json-file-and-put-them-in-an-array
java - How do i get every json elemet in a json file and put them in an array - Stack Overflow
public class App { public static void main( String[] args ) throws Exception { File file = new File("input.json"); String content = new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8"); JSONArray array = new JSONArray(content); //parse ...
🌐
Baeldung
baeldung.com › home › java › java array › convert json object to json array in java
Convert JSON Object to JSON Array in Java | Baeldung
August 24, 2025 - In this article, we explored ways to transform a JSON object to a JSON array using the most popular Java JSON libraries. The org.json library provides us with straightforward tools for both value-only and key-value pair conversions. Jackson excels when working with complex data models or integrating with other Jackson-based features.
🌐
Reddit
reddit.com › r/learnjavascript › how to loop through an array with json objects
r/learnjavascript on Reddit: How to loop through an array with JSON objects
December 30, 2022 -

Hi all,

Im really struggling with this problem today. So basically, I have an array in the format

arr = [{title: " some title", id: "some id"}, {title: " some title2", id: "some id2"}] and all im trying to do is loop through each item in the array and get the value of the ids.

Here is what ive tried:

for( var i = 0; i< arr.length; i++){

console.log(arr[i].id)

}

It keeps showing up as undefined, please can anyone assist me? I would like the result to be "some id"

🌐
Baeldung
baeldung.com › home › kotlin › kotlin collections › iterate through a jsonarray in kotlin
Iterate Through a JSONArray in Kotlin | Baeldung on Kotlin
September 7, 2024 - The JSONArray class doesn’t implement the iterator operator. Hence, we can’t use the typical for-each pattern to iterate a JSONArray.