How to list object key names with jsonpath?

norteo picture norteo · Apr 21, 2013 · Viewed 10k times · Source

I am using nodejs with jsonpath. I have this json structure:

{
  things:{
    books: [
      {name: "book1"},
      {name: "book2"},
      {name: "book3"},
      {name: "book4"},
    ],
    movies: [
      {name: "movie1"},
      {name: "movie2"},
      {name: "movie3"},
      {name: "movie4"},
    ]
  }
}

I would like to know the jsonpath expression that returns an array with the key names of the things object. That would be:

["books","movies"]

For now, I am doing this:

Object.keys(jsonpath.eval(jsonStructure,"$.things").pop());

But I don't find it elegant... I should not need to get a copy the whole structure when I only need the key names.

Answer

Suraj Malgave picture Suraj Malgave · Nov 20, 2019

jsonPath has new update jsonpath-plus jsonpath-plus expands on the original specification to add some additional operators and makes explicit some behaviors the original did not spell out.

^ for grabbing the parent of a matching item ~ for grabbing property names of matching items (as array)

so to get proper output use this query "things.*~" you can try here also https://jsonpath.com/