Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list object key names with jsonpath?

Tags:

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.

like image 612
norteo Avatar asked Apr 21 '13 18:04

norteo


People also ask

How do I specify JSONPath?

You use a JSONPath expression to traverse the path to an element in the JSON structure. You start at the root node or element, represented by $, and reach the required element in the JSON structure to extract data from it. You can use either the dot-notation or the bracket-notation to form the expressions.

What is JSONPath expression?

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as $ regardless if it is an object or array. JsonPath expressions can use the dot–notation.

What is array slice operator in JSONPath?

: operator is the array slice operator, so you can slice collections using the syntax [start:end:step] to return a subcollection of a collection. ( ) operator lets you pass a script expression in the underlying implementation's script language. It's not supported by every implementation of JSONPath, however.

What is the use of JSONPath?

JSONPath is a query language for JSON, similar to XPath for XML. AlertSite API endpoint monitors let you use JSONPath in assertions to specify the JSON fields that need to be verified.


1 Answers

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/

like image 55
Suraj Malgave Avatar answered Sep 17 '22 16:09

Suraj Malgave