114
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

How I can get each item's key and value without knowing the key nor value beforehand?

1

5 Answers 5

327

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}
3
  • 7
    Note: You can't use the short form for (String s: json.keys()) { ... } It's a real shame that neither JSONArray nor JSONObject are iterable. :-( Jun 15, 2015 at 2:25
  • 1
    what is json here? Json Object, Json Array or anthing else? Apr 20, 2016 at 12:50
  • 2
    @PravinsinghWaghela it's a JSONObject as specified in the question Nov 2, 2016 at 18:11
69

Short version of Franci's answer:

for(Iterator<String> iter = json.keys();iter.hasNext();) {
    String key = iter.next();
    ...
}
3
  • what is json here? Json Object, Json Array or anthing else? Apr 20, 2016 at 12:51
  • json is JsonObject Apr 29, 2016 at 20:20
  • @PravinsinghWaghela pretty sure the OP asked how to loop through a json object.
    – Denny
    Nov 11, 2016 at 10:40
8

You'll need to use an Iterator to loop through the keys to get their values.

Here's a Kotlin implementation, you will realised that the way I got the string is using optString(), which is expecting a String or a nullable value.

val keys = jsonObject.keys()
while (keys.hasNext()) {
    val key = keys.next()
    val value = targetJson.optString(key)        
}
0
3

You shold use the keys() or names() method. keys() will give you an iterator containing all the String property names in the object while names() will give you an array of all key String names.

You can get the JSONObject documentation here

http://developer.android.com/reference/org/json/JSONObject.html

-2

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.