Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic use of JSONPath in Java

Tags:

I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.

I gather that Jayway's json-path is the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's version roughly matches up though.

It seems like I ought to be able to do:

String originalJson; //these are initialized to actual data String jsonPath; String queriedJson = JsonPath.<String>read(originalJson, jsonPath); 

The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?

like image 606
Cannoliopsida Avatar asked Jun 25 '14 15:06

Cannoliopsida


People also ask

What is JsonPath used for?

JSONPath is a query language for JSON, similar to XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.

What is the difference between JSON and JsonPath?

JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.

What is JsonPath expression?

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as $ regardless if it is an object or array. JsonPath expressions can use the dot–notation.


2 Answers

Java JsonPath API found at jayway JsonPath might have changed a little since all the above answers/comments. Documentation too. Just follow the above link and read that README.md, it contains some very clear usage documentation IMO.

Basically, as of current latest version 2.2.0 of the library, there are a few different ways of achieving what's been requested here, such as:

Pattern: -------- String json = "{...your JSON here...}"; String jsonPathExpression = "$...your jsonPath expression here...";  J requestedClass = JsonPath.parse(json).read(jsonPathExpression, YouRequestedClass.class);  Example: -------- // For better readability:  {"store": { "books": [ {"author": "Stephen King", "title": "IT"}, {"author": "Agatha Christie", "title": "The ABC Murders"} ] } } String json = "{\"store\": { \"books\": [ {\"author\": \"Stephen King\", \"title\": \"IT\"}, {\"author\": \"Agatha Christie\", \"title\": \"The ABC Murders\"} ] } }"; String jsonPathExpression = "$.store.books[?(@.title=='IT')]";  JsonNode jsonNode = JsonPath.parse(json).read(jsonPathExpression, JsonNode.class); 

And for reference, calling 'JsonPath.parse(..)' will return an object of class 'JsonContent' implementing some interfaces such as 'ReadContext', which contains several different 'read(..)' operations, such as the one demonstrated above:

/**  * Reads the given path from this context  *  * @param path path to apply  * @param type    expected return type (will try to map)  * @param <T>  * @return result  */ <T> T read(JsonPath path, Class<T> type); 

Hope this help anyone.

like image 133
franky duke Avatar answered Oct 05 '22 06:10

franky duke


There definitely exists a way to query Json and get Json back using JsonPath. See example below:

 String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"Ghaziabad\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";  String jsonExp = "$.delivery_codes";  JsonNode pincodes = JsonPath.read(jsonExp, jsonString, JsonNode.class);  System.out.println("pincodesJson : "+pincodes); 

The output of the above will be inner Json.

[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","repl":"N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]

Now each individual name/value pairs can be parsed by iterating the List (JsonNode) we got above.

for(int i = 0; i< pincodes.size();i++){     JsonNode node = pincodes.get(i);     String pin = JsonPath.read("$.postal_code.pin", node, String.class);     String district = JsonPath.read("$.postal_code.district", node, String.class);     System.out.println("pin :: " + pin + " district :: " + district ); } 

The output will be:

pin :: 201001 district :: Ghaziabad

Depending upon the Json you are trying to parse, you can decide whether to fetch a List or just a single String/Long value.

Hope it helps in solving your problem.

like image 25
Ankur Choudhary Avatar answered Oct 05 '22 08:10

Ankur Choudhary