I'm trying to implement a function that given any JSONObject
and a path String
, would return the object's attribute corresponding to the path.
For example, given this json:
{
"name": "John",
"friends": [
{"name": "Paul",
"age":42},
{"name": "Peter",
"age":24}
],
"address": {"city": "London"}
}
getAttribute(jsonObject, "name")
should return "John"
getAttribute(jsonObject, "address.city")
should return "London"
getAttribute(jsonObject, "friends[0].name")
should return "Paul"
Note that this JSON is only an example, jsonObject
has no predefined structure and could represent any valid json.
I wrote a first version implementing the first two cases, but handling arrays and multi-level arrays "foo[0][0].bar"
brings a lot of complexity to this function.
the JSONPath standard by Stefan Goessner covers a more complex syntax, but it also handles the "classic javascript" JSON path syntax.
Using JayWay's implementation for Java, it is trivial to answer the question:
public String getAttribute(JSONObject json, String path) {
return JsonPath.read(json.toString(), path);
}
If I understand your question correctly, you could have potentially already been answered here
Alternatively, you can also try the following open source library:
https://github.com/jayway/JsonPath
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With