Home » Nodejs » How to list object key names with jsonpath?

How to list object key names with jsonpath?

Posted by: admin November 30, 2017 Leave a comment


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

    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:


For now, I am doing this:


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.


I don’t believe there is a better solution than your own:


I think the main misconception here is that you don’t have to worry about this snippet “getting a copy of the whole structure”, because you aren’t copying the whole structure. You already have the entire object loaded into memory, jsonpath doesn’t create a new copy, it simply returns a reference to the already existing object, i.e.:

jsonpath.eval(jsonStructure,"$.things").pop() === jsonStructure.things //true