How to acquire the Key/name of root level JSON Objects with JSONPath?

2.6k views Asked by At

So I have been using jayway JSONPath to query JSON Objects much like the following:

{
  "messageHeader" : {

     "sentBy" : "someOne",
     "userName" : "John Doe"
  },

 "payload" : []
}

And this is working fine for the most part, except now I wish to select the root level objects using the path $..* and preform separate tasks depending on the type of object present in the message, using their key/names as an identifier. However, using said path, or $.* , will always produces a JSONArray much like this:

[{sentBy:someOne,userName:John Doe},[]]

The JSON objects appear to be anonymous, they have no keys. Is there anyway I can access the key for these objects directly as a String? If the data is not present, then why does the path: $.messageHeader.sentBy , work?

1

There are 1 answers

2
johngreen On

From README of the JsonPath :

When evaluating a path you need to understand the concept of when a path is definite. A path is indefinite if it contains:

  • .. - a deep scan operator
  • ?() - an expression
  • [, (, )] - multiple array indexes

Indefinite paths always returns a list (as represented by current JsonProvider).

This should explain the above phenomenon.