Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a subset of attributes with JSONPath

Tags:

I have this JSON code:

{     "A": {         "AB": [{             "ABA": "0",             "ABB": "1",             "ABC": "2"         }]     } } 

I need to use a JSONPath expression that returns that JSON with only ABA and ABC attributes. Something like:

{     "A": {         "AB": [{             "ABA": "0",             "ABC": "2"         }]     } } 

So far I manage to extract either one or all attributes. For example

$.A.AB[*] 

or

$.A.AB[*].ABA 

Is there a way to extract only two?

Thanks

like image 962
Spaffo Avatar asked Dec 12 '14 16:12

Spaffo


People also ask

What is difference between JSON & 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 query?

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.

How do I specify JSONPath?

A JsonPath expression begins with the dollar sign ( $ ) character, which refers to the root element of a query. The dollar sign is followed by a sequence of child elements, which are separated via dot (code) notation or via the square brackets (code).

What is JSONPath in Java?

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is available in many programming languages such as Javascript, Python and PHP. JsonPath allows you to compile a json path string to use it many times or to compile and apply in one single on demand operation.


1 Answers

This will work using the Jayway implementation (Java):

$.A.AB[*]['ABB', 'ABA'] 

and the result for your input would be:

[    {       "ABB" : "1",       "ABA" : "0"    } ] 

You can Compare different providers here:

http://jsonpath.herokuapp.com/

like image 197
kalle Avatar answered Oct 10 '22 03:10

kalle