How to extract Data from JSON Payload?

snow_04
Giga Contributor

Hi,

How can we extract data from response coming in JSON format? Like for example as mentioned below:

{"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"}

Currently what I am doing in background script is as below:

var str = {"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"};

gs.info(JSON.stringify(str.status));  -- Getting Correct Output as "2".

Can someone please assist on how to extract the elements present within response attribute JSON, like I want to extract objects like "Ticket" , "StatusCode" which are within the Response Object etc.

 

Currently if I do something as below it gives me undefined:

 

gs.info(JSON.stringify(str.response.IncidentId));

 

Kindly assist!!

 

 

17 REPLIES 17

Mukesh Arora2
Tera Expert

You can use JSON.parse like below:

 

var obj = JSON.parse(str);

obj.state or obj.statecode etc.

 

Let me know if that works.

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

try this script in background

var str = '{"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"}';

var finalStr = str.replaceAll('"{','{');

var finalStr = finalStr.replaceAll('}"','}');

var parser = new JSONParser();

var parsedData = parser.parse(finalStr);

gs.info(parsedData.response.Ticket);  

gs.info(parsedData.response.StatusCode);

gs.info(parsedData.response.Message);

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

HI Ankur,

 

This works perfectly fine, but can you please explain me why JSON.parse did not work as stated below by other folks?

Hi,

that's because there is an extra double quotes before { and extra double quotes after }

that is what I have removed and then did the parsing

it works with JSON.parse() as well

var str = '{"state":2,"httpCode":200,"response":"{\"Ticket\" : \"061cech41hh7e27c86f88b08c8fd2a\",\"StatusCode\" : \"201 Created\",\"Message\" : \"Record Created.\"}"}';

var finalStr = str.replaceAll('"{','{');

var finalStr = finalStr.replaceAll('}"','}');

var parser = JSON.parse(finalStr);

gs.info(parser.response.Ticket);  

gs.info(parser.response.StatusCode);

gs.info(parser.response.Message);

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader