Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a JSONObject?

Tags:

java

json

I use a JSON library called JSONObject (I don't mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSON data from Facebook I don't get an array, only a JSONObject, but I need to be able to access an item via its index, such as JSONObject[0] to get the first one, and I can't figure out how to do it.

{    "http://http://url.com/": {       "id": "http://http://url.com//"    },    "http://url2.co/": {       "id": "http://url2.com//",       "shares": 16    }    ,    "http://url3.com/": {       "id": "http://url3.com//",       "shares": 16    } } 
like image 626
Eric Hjalmarsson Avatar asked Feb 05 '12 18:02

Eric Hjalmarsson


People also ask

How do I iterate through a JSON object?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

Can you iterate through JSON?

We can use Object. entries() to convert a JSON array to an iterable array of keys and values. Object. entries(obj) will return an iterable multidimensional array.

How do I iterate through a JSON object in typescript?

The Best Answer isforEach(element => { list. push(element.Id); });


2 Answers

Maybe this will help:

JSONObject jsonObject = new JSONObject(contents.trim()); Iterator<String> keys = jsonObject.keys();  while(keys.hasNext()) {     String key = keys.next();     if (jsonObject.get(key) instanceof JSONObject) {           // do something with jsonObject here           } } 
like image 166
Rickey Avatar answered Sep 21 '22 21:09

Rickey


for my case i found iterating the names() works well

for(int i = 0; i<jobject.names().length(); i++){     Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i))); } 
like image 36
AssemblyX Avatar answered Sep 22 '22 21:09

AssemblyX