How to access JSON values inside Variable (maintain items) in ServiceNow

fjdb
Tera Contributor

Hello. This may be a very basic question but I haven't found much references. 

How can I access JSON value from a field in "variables" maintain items in ServiceNow? User inputs where stored inside JSON and I want to access the values stored in each key. 

Example : 

Variable field under maintain items: EmployeeData 

JSON keys are: age , gender , height

 

How can I access it via server script? 

Thank you so much. 

 

1 ACCEPTED SOLUTION

AshishKM
Kilo Patron

Hi @fjdb ,

Try with below sample code for reading JSON object in catalog item. I think, you are trying the read JSON in workflow.

 

Sample JSON 

{"age":"15", "gender":"m","height":"168"}

Use the below code

var jsonObj =  current.variables.<jsonVariableName>.toString();

var str = JSON.stringify(jsonObj );

var parser = new JSONParser();

var result = parser.parse(str);

gs.print(‘age: ’+result.age);

 

If JSON has more than one set of data then, we have iterate the result object.

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

        gs.info(result[i].age);

}

 

-Thanks,
AshishKMishra

Please accept solution and mark helpful if it helps you

 

 

View solution in original post

1 REPLY 1

AshishKM
Kilo Patron

Hi @fjdb ,

Try with below sample code for reading JSON object in catalog item. I think, you are trying the read JSON in workflow.

 

Sample JSON 

{"age":"15", "gender":"m","height":"168"}

Use the below code

var jsonObj =  current.variables.<jsonVariableName>.toString();

var str = JSON.stringify(jsonObj );

var parser = new JSONParser();

var result = parser.parse(str);

gs.print(‘age: ’+result.age);

 

If JSON has more than one set of data then, we have iterate the result object.

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

        gs.info(result[i].age);

}

 

-Thanks,
AshishKMishra

Please accept solution and mark helpful if it helps you