How to Iterate Over a Jsonobject

Iterate through JSONObject from root in json simple

Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:

JSONParser parser = new JSONParser();

Object obj = parser.parse(new FileReader("simple.json"));

JSONObject jsonObject = (JSONObject) obj;

for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}

Loop through multiple JsonObject

As per your code you just get the key and value of the first object.

JSONObject jsonObject = new JSONObject(json);

from above code, you just get the first object from JSON.

Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = jsonObject.get(key.toString());
response.add(value);
}

From above code, you will get the key and values of first JSON object.

Now, if you want to get all object value then you have to change your code as per below :

Change JSON like below:

[{
"name": "Jane John Doe",
"email": "janejohndoe@email.com"
},
{
"name": "Jane Doe",
"email": "janedoe@email.com"
},
{
"name": "John Doe",
"email": "johndoe@email.com"
}]

Change java code as per below:

List<HashMap<String,String>> response = new ArrayList<>();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(json);
for(int i=0;i<jsonarray.length();i++) {
JSONObject jsonObject = jsonarray.getJSONObject(i);
Iterator<?> iterator = jsonObject.keys();
HashMap<String,String> map = new HashMap<>();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = jsonObject.get(key.toString());
map.put(key.toString(),value.toString());

}
response.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}

JSON - Iterate through JSONArray

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

Iterate through JSONObject

I found the solution by trial and error. There is way of iteration like in Json Array:

jsonObject.each {
// do something with it.key and it.value pair
}

Iterating through a JSON object

Your loading of the JSON data is a little fragile. Instead of:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

you should really just do:

json_object = json.load(raw)

You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].

None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.

how to iterate through this json object and format it

I would Approach this this way:

  1. Create a main class that holds all the information of the JSON and a Secondary class that keeps the information of the prop properties of the JSON:
public class MainJsonObject
{
private int $id;
private int $schema;

// All the other objects that you find relevant...

private List<SecondaryJsonObject> propsList = new ArrayList<>(); // This will keep all your other props with description and type

// Getter and setter, do not forget them as they are needed by the JSON library!!

}

public class SecondaryJsonObject
{
private String description;
private String type;

// Getter and setter, do not forget them !!
}

  1. You could iterate through your JSON Object this way:

First of all include the JSON Library in your project.

Then iterate through your JSON like this:

JSONObject jsonObject = new JSONObject(jsonString);

MainJsonObject mjo = new MainJsonObject();
mjo.set$id(jsonObject.getInt("$id")); // Do this for all other "normal" attributes

// Then we start with your properties array and iterate through it this way:

JSONArray jsonArrayWithProps = jsonObject.getJSONArray("properties");

for(int i = 0 ; i < jsonArrayWithProps.length(); i++)
{
JSONObject propJsonObject = jsonArrayWithProps.getJSONObject(i); // We get the prop object

SecondaryJsonObject sjo = new SecondaryJsonObject();
sjo.setDescription(propJsonObject.getString("description"));
sjo.setTyoe(propJsonObject.getString("type"));

mjo.getPropsList().add(sjo); // We fill our main object's list.

}

How do I loop through or enumerate a JavaScript object?

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet: