JavaScript: JSONPath

Introduction

In this tutorial, we will check how to apply JSONPath expressions to query JSON objects and obtain the values of the properties.

JSONPath is a query language for JSON, (similar to XPath for XML) [1] that allows us to selectively access parts of our JSON.

We will be using the JSONPath plus library to be able to apply the expressions. We can install it with NPM with the following command:

npm install jsonpath-plus

The code

We will start by importing the JSONPath function from the installed module.

const {JSONPath} = require('jsonpath-plus');

Then we will define an object with some properties that we will use to query.

const obj = {
    prop1: 10,
    prop2: "test",
    prop3: {
        nestedProp: "nested"
    },
    prop4: ["elem1", "elem2"],
}

To query a JSON object, we simply need to call the JSONPath function we have just imported. As input, we pass an object with the following properties:

  • path: a string containing the JSONPath expression we want to apply;
  • json: the object we want to query.

Note that there are some additional properties that we can pass on this object, as can be seen on the documentation. We will make use of one of these properties later, for illustration purposes.

So, the first exercise we will do is getting the values of the 4 top level properties we have. To access a property in the root of the object, we can use the following syntaxe:

$.propertyName

Note that $ corresponds to the root of the object and .propertyName is how we select a property in a parent object [1].

To obtain the values of each of the four properties of the object, we can use the code shown below:

console.log(JSONPath({path: "$.prop1", json: obj}));
console.log(JSONPath({path: "$.prop2", json: obj}));
console.log(JSONPath({path: "$.prop3", json: obj}));
console.log(JSONPath({path: "$.prop4", json: obj}));

To see some additional possibilities, we will now check how to access the nested property we have in our JSON. In terms of syntax, we can chain the .propertyName expression multiple times to drill down over nested properties.

console.log(JSONPath({path: "$.prop3.nestedProp", json: obj}));

To select elements from an array, such as prop4, we can use the [] operator, putting the index of the element inside brackets.

console.log(JSONPath({path: "$.prop4[0]", json: obj}));
console.log(JSONPath({path: "$.prop4[1]", json: obj}));

We will also see an example where we look for a property that doesn’t exist:

console.log(JSONPath({path: "$.nonExistingProp", json: obj}));

To finalize our code, we will make use of an optional property of the object we pass as input of the JSONPath function. We will use the wrap property, which allows to set if we want the result of the expressions to be wrapped in an array or not.

Note that this property defaults to true, which means all the previous results will be returned wrapped in an array. So, we will set the property to false here, meaning the result will not be wrapped.

console.log(JSONPath({path: "$.prop1", json: obj, wrap: false}));

The final code can be seen below.

const {JSONPath} = require('jsonpath-plus');

const obj = {
    prop1: 10,
    prop2: "test",
    prop3: {
        nestedProp: "nested"
    },
    prop4: ["elem1", "elem2"],
}

console.log("Top level props:");
console.log(JSONPath({path: "$.prop1", json: obj}));
console.log(JSONPath({path: "$.prop2", json: obj}));
console.log(JSONPath({path: "$.prop3", json: obj}));
console.log(JSONPath({path: "$.prop4", json: obj}));

console.log("\n\nNested prop:");
console.log(JSONPath({path: "$.prop3.nestedProp", json: obj}));

console.log("\n\nArray elements:");
console.log(JSONPath({path: "$.prop4[0]", json: obj}));
console.log(JSONPath({path: "$.prop4[1]", json: obj}));

console.log("\n\nNon Existing prop:");
console.log(JSONPath({path: "$.nonExistingProp", json: obj}));

console.log("\n\nWithout array wrap:");
console.log(JSONPath({path: "$.prop1", json: obj, wrap: false}));

Testing the code

To test the previous code, simply run it in a tool of your choice. In my case, I’m using Visual Studio Code with the Code Runner extension. I’m also using node.js version 14.3.0.

You should obtain a result similar to figure 1. As can be seen in the first group of prints, we obtained the values of the properties in the root of the object. Then, we obtained the nested property value.

After that, we can see both elements of the array getting printed, as expected. For the case where the property was not found, an empty array was returned. To finalize, in the last print, we can see that the result was not wrapped in an array.

Output of the program in Visual Studio Code, with the result of the JSONPath expressions.
Figure 1 – Output of the program in Visual Studio Code.

Related JavaScript Posts

References

[1] https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading