Skip to content

Commit e946ac1

Browse files
authored
Merge pull request #1705 from SrijanPatwa/get-key-value-from-json
Extract Key and Value from JSON Object
2 parents 5d284c5 + 6b01c99 commit e946ac1

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//JSON of username and corresponding title
2+
3+
var userData = {
4+
"userDetails": [{
5+
"user_name": "dennis.millar",
6+
"title": "Account Exec Northeast"
7+
},
8+
{
9+
"user_name": "ashley.parker",
10+
"title": "Director"
11+
},
12+
{
13+
"user_name": "steve.schorr",
14+
"title": "Investigations Generalist"
15+
},
16+
{
17+
"user_name": "tammie.schwartzwalde",
18+
"title": "Senior Auditor"
19+
},
20+
{
21+
"user_name": "tammie.schwartzwalde",
22+
"title": "Payroll Generalist"
23+
},
24+
{
25+
"user_name": "tommy.tom",
26+
"title": "Tester"
27+
},
28+
]
29+
};
30+
31+
32+
var userRoles = {};
33+
for (var i = 0; i < userData.userDetails.length; i++) {
34+
var user = userData.userDetails[i];
35+
if (!userRoles[user.user_name]) {
36+
userRoles[user.user_name] = [];
37+
}
38+
39+
if (userRoles[user.user_name].indexOf(user.title) === -1) {
40+
userRoles[user.user_name].push(user.title);
41+
}
42+
}
43+
44+
45+
for (var userName in userRoles) {
46+
gs.info("User: " + userName + " having Role(s): " + userRoles[userName].join(", "));
47+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Open 'Scripts - background' in ServiceNow and run the script of [extractValueFromJSON.js] file.
2+
3+
This also checks for the duplicate user_name and shows the unique ones and the corresponding roles of that particular user.
4+
5+
6+
Script:
7+
8+
<img width="556" height="636" alt="image" src="https://github.com/user-attachments/assets/8300e272-a712-4b4d-bf91-6e2d8df0aa6b" />
9+
10+
11+
Result:
12+
13+
<img width="937" height="167" alt="image" src="https://github.com/user-attachments/assets/51ed18d3-ec65-4812-9298-0fc43bd7bec6" />
14+
15+

0 commit comments

Comments
 (0)