22

I get the following JSON result from an external system:

{
  "key1": "val1",
  "key2": "val2",
  "key3": "val3"
}

Now I want to display all keys and all values by using JSONPath. So I am looking for something to get key1, key2 and key3 as a result. Additionally I would like to use the index of a property, e. g. $....[2].key to get "key3" etc. Is there a way to do something like this?

Stefan
  • 1,253
  • 2
  • 12
  • 36
  • Have you looked at Object.keys( ) ? – semuzaboi Sep 28 '17 at 14:23
  • I just need the JSONPath expression (as you can test it at jsonpath.com) for that to use it in my system. Unfortunately I am not able to use javascript or any other code. I just can pass an JSONPath expression as a parameter... – Stefan Sep 29 '17 at 09:17

2 Answers2

41

I found that the tilda ~ symbol is able to retrieve the keys of the values it's called upon. So for your example a query like this:

$.*~

Returns this:

[
  "key1",
  "key2",
  "key3"
]

Another example, if we had a JSON document like this:

  {
  "key1": "val1",
  "key2": "val2",
  "key3": {
      "key31":"val31",
      "key32":"val32"
  }
}

A query like this:

$.key3.*~

Would return this:

[
  "key31",
  "key32"
]

It's important to note that these examples work on JSONPath.com and some other simulators/online tools, but on some they don't. It might come from the fact that I found out about the tilda(~) operator in the JSONPath plus documentation and not the official one.

Viktor
  • 2,623
  • 3
  • 19
  • 28
  • Helpful answer, but for some reason doesn't work within `kubectl get .. -o jsonpath=` command. It returns list of values if i do `$.key.*`. But it returns empty list if i do `$.key.*~` or `$.key*~` – Alexander Tereshkov Oct 28 '22 at 20:18
  • If, like me, you are using Java and Spring's `JsonPathResultMatchers` you have to use `$.keys()`. None of the above will be interpreted as expected. – Arturo Mendes Aug 30 '23 at 12:02
0

For the java json path use below expression:

 private static Configuration getConfiguration() {
        return Configuration.builder().options(Option.AS_PATH_LIST).build();
    }
    DocumentContext parsedBodyWithJsonPath = using(getConfiguration()).parse(jso);
    List<String> read = parsedBodyWithJsonPath.read("$.*");
    System.out.println("keys: "+read);

output :

keys: ["$['key1']","$['key2']","$['key3']"]

Hasan Khan
  • 554
  • 1
  • 7
  • 23