How to parse a JSON response in a Client script coming from script include ?

Subhashree Sub1
Tera Contributor

Hi All,

I am trying to retrieve JSON objects in a client script which receives the JSON response from a Script include through GlideAJAX. However, I am unable to make it work inside the Client script by using JSON.parse and several other ways that I have tried.

Script include:

find_real_file.png

Client Script:

find_real_file.png

Response coming from Script include:

find_real_file.png

 

Please let me know how to retrieve an object from this response in the client script. I am trying to do in onSubmit client script.

 

Thank you!

1 ACCEPTED SOLUTION

_ChrisHelming
Tera Guru

Your JSON object stores the information in an array in the result property. You need to "dot walk" to the result, and to a specific item in the array before you can get the mac address.

alert(answer.result[0].mac_address);

if you think you might ever have more than one result you'll need to loop over the results:

answer.result.forEach(function(infobloxRecord){
   alert(infobloxRecord.mac_address);
   // do something with infobloxrecord.ip_address, .network, ._ref, whatever
}

View solution in original post

9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

so what you wish to get from the JSON object?

your json seems wrong

Can you share your script include code and client script code

Regards
Ankur

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

Hi Ankur,

I have updated my question sharing the script details. Please have a look and post your suggestions.

Thank you!

share the scripts and not screenshots

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

Adrian Ubeda
Mega Sage
Mega Sage

Hi Subhashree,

Try to use JSON.parse() and JSON.stringify() I let you some examples about how your JSON object built should be:

//Script include

var scriptIncludeName= Class.create();
scriptIncludeName.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	
    methodName:function(){
        var jsonData = {
             "result": "OK",
             "argument": 'param',
        };        
        return JSON.stringify(jsonData); // Encodes json into a string and returns it.
    }
}
//Client Script

function callback(response){
    // Use documentElement and "answer" is a fixed value
    var answer =  response.responseXML.documentElement.getAttribute('answer');
    
    try{
        // It's unlikely, but it's better to define exceptions
        answer = JSON.parse(answer); // Convert json string to object
    }
    catch(e){
        alert(e);
        return;
    }
    alert(answer.result);   // value="OK"
    alert(answer.argument); // value="param"
}

If it was helpful, please give positive feedback.
Thanks,

If it was helpful, please give positive feedback! ✔
☆ Community Rising Star 22, 23 & 24 ☆