How can I get a nested value in a JSONObject from its path?
<p>I'm trying to implement a function that given any <code>JSONObject</code> and a path <code>String</code>, would return the object's attribute corresponding to the path.</p>

<p>For example, given this json:</p>

<pre><code>{
"name": "John", 
"friends": [
  {"name": "Paul",
   "age":42},
  {"name": "Peter",
   "age":24}
 ],
"address": {"city": "London"}
}
</code></pre>

<ul>
<li><code>getAttribute(jsonObject, "name")</code> should return <code>"John"</code></li>
<li><code>getAttribute(jsonObject, "address.city")</code> should return <code>"London"</code></li>
<li><code>getAttribute(jsonObject, "friends[0].name")</code> should return <code>"Paul"</code></li>
</ul>

<p><strong>Note that this JSON is only an example, <code>jsonObject</code> has no predefined structure and could represent any valid json.</strong></p>

<p>I wrote a first version implementing the first two cases, but handling arrays and multi-level arrays <code>"foo[0][0].bar"</code> brings a lot of complexity to this function.</p>

<h2>Is there a recommended tool/library/method for getting an attribute from a JSONObject given a "complex" path?</h2>