Muralidharan BS
Mega Sage
Mega Sage

GlideJsonPath API

 

I like to work with JSON, ServiceNow in Vancouver has introduced a new API related to JSON which is **GlideJsonPath.**

 

I find this API very useful as it helps reduce the amount of code needed when working with JSON.

 

I have referred to many different sources and discovered a couple of useful features. Here are a few of the use cases.

 

$ root element
* wild card
[,] array
?(@)

script with the current object

 

 

var js = {
    "task": {
        "incident": [
            {
                "number": "INC12345",
                "state": "open"
            },
            {
                "number": "INC12346",
                "state": "in progress"
            },
            {
                "number": "INC12347",
                "state": "in progress"
            }
        ],
        "user": {
            "active": true
        }
    }
}

 

 

1. Use a dot to travel in the path of JSON

 

var gjp = new GlideJsonPath(JSON.stringify(js)); 
var numbers = gjp.read("$.task.*");
gs.print(numbers)
gs.print(' Type ' + Object.prototype.toString.call(numbers));

 

output

MuralidharanBS_1-1708281922602.png

2. Getting specific items from the array 

 

var gjp = new GlideJsonPath(JSON.stringify(js)); 
var numbers = gjp.read("$.task.incident[0,1]");
gs.print(numbers)
gs.print(' Type ' + Object.prototype.toString.call(numbers));

 

output

MuralidharanBS_2-1708282026321.png

 

3. Using a script to filter the only open state incident

 

var gjp = new GlideJsonPath(JSON.stringify(js)); 
var numbers = gjp.read("$.task.incident[?(@.state=='open')]");
gs.print(numbers)
gs.print(' Type ' + Object.prototype.toString.call(numbers));

 

 

output

MuralidharanBS_3-1708282080802.png

These are a couple of examples which might be useful when interacting with JSON. There are many more use cases, and we will try to keep this article updated. Don't forget to drop in and check for updates.

 

Thanks

Murali

LinkedIn

Version history
Last update:
‎02-18-2024 10:50 AM
Updated by:
Contributors