We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

How to create JSON array in following format.

Para5
Tera Guru

I have following requirement.

I want Json array such that :

 

"UserandRoles":[  

 

                      {  

 

                            "name":"Abel",

 

                            "role":"admin"

 

                      },

 

                      {  

 

                            "name":"Abel",

 

                            "role":"security_admin"

 

                      },

                       {  

 

                            "name":"John",

 

                            "role":"itil"

 

                      }

 

                ]

Script is as below:

var info = [];

var Information = {};

 

var gr = new GlideRecord('sys_users');

gr.addQuery('sys_id',  usersys);

gr.query();

if( gr.next()){

 

info.name = gr.name.getDisplayValue();
info.Roles = gr.u_roles.getDisplayValue(); // u_role field contain roles in folllowing format role1, role2, role3....

info .push(Information );

 

}

 

Thanks,

 

1 ACCEPTED SOLUTION

newhand
Mega Sage

@Para5 



var infoList = []
var Information = {};
var gr = new GlideRecord('sys_user');

gr.addQuery('sys_id', usersys);

gr.query();

if( gr.next()){


var info = {}
var user_name = gr.name.getDisplayValue();

var roles_arr = gr.roles.split(','); // u_role field contain roles in folllowing format role1, role2, role3....

for (var i = 0; i < roles_arr.length; ++i) {

info.name = user_name
info.role = roles_arr[i]
infoList.push(info);

}

}
Information.UserandRoles = infoList
gs.info(JSON.stringify(Information))

Please mark my answer as correct and helpful based on Impact.

View solution in original post

5 REPLIES 5

jaheerhattiwale
Mega Sage

@Para5 Tried and tested solution.

 

var mainObject = {
    "UserandRoles" : []
}

var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('user',  usersys);
gr.query();

while( gr.next()){
    var infoObject = {};
    infoObject.name = gr.user.getDisplayValue();
    infoObject.role = gr.role.getDisplayValue();
    mainObject["UserandRoles"].push(infoObject);
}

gs.info(JSON.stringify(mainObject));
 
Please mark as correct answer if this solves your issue.
Please mark the answer as correct or helpful based on impact
ServiceNow Community Rising Star, Class of 2023