parsing JSON

deepika46
Tera Contributor

Hello experts,

 

consider a JSON which i am receiving through inbound integration and i am using scripted rest api

example

{"incident":"123" , "state" :"2" , "descript":"orange"}

 

First i have to check if the JSON is empty or not 

2nd i have to check if the JSON contains the key state or not like the JSON should not contain {"incident":"123,"descript":"orange"}

 

If i receive a JSON based on these 2 conditions

 

I have to send http status code of 500.

 

Can anyone help me. 

2 ACCEPTED SOLUTIONS

Sandeep Rajput
Tera Patron
Tera Patron

@deepika46 Here is the code you should use.

var jsonString= '{"incident":"123" , "state" :"2" , "descript":"orange"}';
var jsonObj = JSON.parse(jsonString);
var httpStatus = '';
if(!gs.nil(jsonObj) &&!gs.nil(jsonObj["state"])){
    gs.info('valid object');    
    httpStatus = '500';
}
else{
    gs.info('not valid');
    httpStatus = '400';
}

Hope this helps.

View solution in original post

Vishal Birajdar
Giga Sage

Hi @deepika46 

 

Can you try below code :

 

    var  yourSON ={"incident":"123" , "state" :"2" , "descript":"orange"};
    
    try {
        var parsedJSON = JSON.parse(yourJSON); // Parse the received JSON string
        if (!parsedJSON) {
            gs.log("Empty JSON");
            return;
        } else if (!parsedJSON.hasOwnProperty('state')) {
            gs.log("JSON does not contain the 'state' key.");

            //Set the response code to 500
        } else {     
            // Continue to do
        }
    } catch (err) {
        // Handle the error/exception 
    }

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

View solution in original post

2 REPLIES 2

Sandeep Rajput
Tera Patron
Tera Patron

@deepika46 Here is the code you should use.

var jsonString= '{"incident":"123" , "state" :"2" , "descript":"orange"}';
var jsonObj = JSON.parse(jsonString);
var httpStatus = '';
if(!gs.nil(jsonObj) &&!gs.nil(jsonObj["state"])){
    gs.info('valid object');    
    httpStatus = '500';
}
else{
    gs.info('not valid');
    httpStatus = '400';
}

Hope this helps.

Vishal Birajdar
Giga Sage

Hi @deepika46 

 

Can you try below code :

 

    var  yourSON ={"incident":"123" , "state" :"2" , "descript":"orange"};
    
    try {
        var parsedJSON = JSON.parse(yourJSON); // Parse the received JSON string
        if (!parsedJSON) {
            gs.log("Empty JSON");
            return;
        } else if (!parsedJSON.hasOwnProperty('state')) {
            gs.log("JSON does not contain the 'state' key.");

            //Set the response code to 500
        } else {     
            // Continue to do
        }
    } catch (err) {
        // Handle the error/exception 
    }

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates