I have JSON structure that is a nested parent/child kind of structure:
{
"type": "site",
"profile_id": "site profile id",
"children": [
{
"type": "dealer",
"profile_id": "dealer profile id",
"children": [
{
"type": "location",
"profile_id": "location profile id",
"children": [
{
"type": "customer",
"profile_id": "customer profile id",
"children": [
{
"type": "farm",
"farm_id": "farm id",
"children": [
{
"type": "field",
"field_id": "field id"
}]}]}]}]}]}
Is there some way in JSONPath to do one of the following:
give me the profile_id if it's present, or give me the farm_id if it's present, or give me the field_id if it's present.
give me the profile_id if type=customer, or give me the farm_id, if type=farm, or give me the field_id if type=field
give me the nth attribute from each class. The id is actually the third attribute in each class. This is my least favorite option, because I don't know if the id will always be the third attribute.
A JSONPath expression specifies a path to an element (or a set of elements) in a JSON structure. Paths can use the dot notation: $.store.book[0].title. or the bracket notation: $['store']['book'][0]['title']
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.
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).
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.
A solution for option 2 that requires 3 separate queries would be the following. Here are the 3 queries:
$..[?(@.type=='customer')].profile_id
$..[?(@.type=='farm')].farm_id
$..[?(@.type=='field')].field_id
I verified these queries with http://www.jsonquerytool.com
Also see this question for a similar example.
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