JSON - Iterate through JSONArray

JavaJson

Java Problem Overview


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": {
    "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"
        }

    ]
}

}		

This is how far I have come:

JSONObject object = new JSONObject("json-file.json");
JSONObject getObject = object.getJSONObject("JObjects");
JSONArray getArray = getObject.getJSONArray("JArray1");

for(int i = 0; i < getArray.length(); i++)
{
      JSONObject objects = getArray.getJSONArray(i);
      //Iterate through the elements of the array i.
      //Get thier value.
      //Get the value for the first element and the value for the last element.
}

Is it possible to do something like this?

The reason I want to do it like this is because the arrays in the file have a different number of elements.

Java Solutions


Solution 1 - Java

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
*/

Solution 2 - Java

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

Solution 3 - Java

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

Solution 4 - Java

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type: > The values can be any of these types: Boolean, JSONArray, JSONObject, > Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

Solution 5 - Java

To use @aianitro's efficient solution to cases like io.vertx.core.json.JsonArray where the iterator returns Object, cast the object to JsonObject afterwards...

Iterator<Object> it = timeseries.iterator();
while(it.hasNext()){
    JsonObject jobj = (JsonObject) it.next();
    System.out.println(jobj);
}

Solution 6 - Java

You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object
        
        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down
        
        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {
        
        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErikView Question on Stackoverflow
Solution 1 - JavaProgrammer BruceView Answer on Stackoverflow
Solution 2 - JavaMartinView Answer on Stackoverflow
Solution 3 - JavaaianitroView Answer on Stackoverflow
Solution 4 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 5 - JavantgView Answer on Stackoverflow
Solution 6 - JavaSameer TechnomarkView Answer on Stackoverflow