Get elements in JSONObject

I try to go in JSONObject but I don’t find a solution to go inside, except if I use knew key. But my purpose is going to the object to grad all informations from it, I don’t know the information in advance.
I see the JSONObject is an HashMap, but when I try to apply the function from HashMap like values() this function is not recognize, but size() yes.

    JSONObject list = item.getJSONObject("density");
    println("list",list);
    println("list size",list.size());

console log

list {
  "gaz": 1.429,
  "liquid": 1.141
}
list.size() 2

but when I try

    for(Float f : list.values()) {
      println("float", f);
    }

the console return

R_Atom.pde:53:0:53:0: The function values() does not exist.

I try the classic way too with

for(int i = 0 ; i < list.size() ; i++) {
   println(list.get(i));
}
R_Atom.pde:65:0:65:0: The method get(String) in the type JSONObject is not applicable for the arguments (int)

So my question is how loop in JSON Object to grab the object ?

1 Like

Indeed it relies on a HashMap internally.

But we’re not supposed to interact w/ it directly b/c it’s private:

This is the whole list of methods for it:
http://Processing.GitHub.io/processing-javadocs/core/processing/data/JSONObject.html

For looping we can use methods keyIterator() or keys():

2 Likes

I found the solution, but I must will go deep in Processing core

    Object [] objets = list.keys().toArray();
    for(int i = 0 ; i < list.size() ; i++) {
      println("key:",objets[i], ", value:", list.get((String)objets[i]));
    }

console

key: gaz, value: 1.429
key: liquid, value: 1.141

May be that’s can be good to add this examples in the Processing documentation and add keys() function in the JSONObject / Reference / Processing.org

3 Likes

find in the same time :slight_smile:

2 Likes