Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Take value from JSON payload and add it to choice variable

Jake Adams
Tera Contributor

Hi,

I am trying to fetch a value from the JSON payload and trying it to push it to a Selectbox variable as choices by using g_form,addOption but it's returing as [object] [object] or [Null]

 

[
    {
        "self": "123",
        "id": "456",
        "description": "",
        "name": "Mark"
    },
    {
        "self": "789",
        "id": "980",
        "description": "",
        "name": "Ben"
    },
    {
        "self": "678",
        "id": "888",
        "description": "",
        "name": "Mike"
    }]
 
I want to get the name from the payload and add it the choice variable
 
 

 

1 ACCEPTED SOLUTION

Thanks, so option variable in your example represents an object. You need to instead pass a string to addOption. It depends on what you want your dropdown list to display exactly. For example, if you want just the name displayed it would be option.name:

 

g_form.addOption('variablename', option.name, option.name, index + 1);

 

 

View solution in original post

4 REPLIES 4

Nick Parsons
Mega Sage

Can you please share the code you're using? [object Object] normally means you're trying to convert an object into a string (most likely unintentionally).

Hi Nick,

 

SI:

 

getNames: function() {
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('get');    
        var endpoint = gs.getProperty('Endpoint stored in the property');
        request.setEndpoint(endpoint);
        request.setAuthenticationProfile('basic', gs.getProperty('Name of the property'));

        response = request.execute();
        httpResponseStatus = response.getStatusCode();

        if (httpResponseStatus != 200) {
            return 'error';
        }

        return response.getBody();
 
Client Script:
 
function onLoad() {
 
    var ga = new GlideAjax('SI name');
    ga.addParam('sysparm_name', 'getNames');
    ga.getXML(function(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
//alert('The Result: ' + answer);
        if (answer == 'error') {
 
 
        } else {
            var options = JSON.parse(answer);
            options.forEach(function(option, index) {
            g_form.addOption('variablename', option, option, index + 1);
            });
        }
    });
}

Thanks, so option variable in your example represents an object. You need to instead pass a string to addOption. It depends on what you want your dropdown list to display exactly. For example, if you want just the name displayed it would be option.name:

 

g_form.addOption('variablename', option.name, option.name, index + 1);

 

 

Thanks a lot.

 

That worked.