Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a nested value in a JSONObject from its path?

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.

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

like image 461
PLNech Avatar asked Nov 24 '16 10:11

PLNech


2 Answers

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);
}
like image 98
PLNech Avatar answered Oct 25 '22 15:10

PLNech


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

like image 3
rares.urdea Avatar answered Oct 25 '22 14:10

rares.urdea