How to Loop Through JSON Array

How to loop through JSON array and get specific values

in your loop:

for (x in myObj) {
alert(x.car1);
}

x is the string value of key of your object. In order to get the car1 property of your nested object you can change your loop as:

for (x in myObj) {
alert(myObj[x].car1);
}

It is also a good practice to use hasOwnProperty while using for-in loop it might also iterate over properties which are in your object's prototype chain.

for (x in myObj) {
if (myObj.hasOwnProperty(x)) {
alert(myObj[x].car1);
}
}

How do I loop through a JSON array?

You can use for..in loops on objects to get the keys and iterate over them. Objects don't implement the Iterable interface, so for...of doesnt work. And forEach is not a method on an object, but on an array.

const json = {
"channels": {
"main": {
"id": "691548147922763825"
},
"creations": {
"id": "700390086390448148"
},
"fanart": {
"id": "691551615873843211"
},
"memes": {
"id": "691549417173680148"
}
}
}

for( let key in json.channels ) {
console.log( key, json.channels[key] )
}

How to iterate through JSON array in angular

Given that each object is contained in an array, I assume that each property could contain more than one object as values. You could try the following.

I am assigning the respone from the API to a variable called countries.

Controller

countries = [];

getData() {
this.apiService.getCountries().subscribe(
response => { this.countries = response; },
error => { // handle error }
);
}

Template

<div *ngFor="let country of countries">
<label>Country Capital:</label>
<p>{{ country.capital }} </p>
<label>Languages:</label>
<p *ngFor="let language of country.languages">{{ language.name }}</p>
<label>Currencies:</label>
<p *ngFor="let currency of country.currencies">{{ currency.name }}</p>
</div>

Update

There is an issue with the interface definition. The languages property is defined as an array of type string whereas it's a custom object. You could define a separate interface for each type of object. Try the following

export interface Country {
name: string;
topLevelDomain?: string[];
alpha2Code?: string;
languages?: Language[];
currencies?: Currency[];
translations?: Translate[];
regionalBlocs?: RegionalBloc[];
.
.
.
}

export interface Language {
iso639_1:? string;
iso639_2:? string;
name:? string;
nativeName:? string;
}

And the same goes for other properties currencies, translations and regionalBlocs. Each need their own interface definitions similar to the one shown here for languages.

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

Looping through a JSON array in Python

When restaurants is your list, you have to iterate over this key:

for restaurant in data['restaurants']:
print restaurant['restaurant']['name']

Jquery How to loop through JSON array and keep adding the value

You can try like below :

var usedAccu = 0
var jData = [{
"key1": "1",
"key2": "5",
}, {
"key1": "1",
"key2": "22",
}]
$.each(jData, function(key, value) {
usedAccu += parseInt(value.key2) //change to your required keyname
});
console.log(usedAccu)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Related Topics



Leave a reply



Submit