How to Parse Object

Supriya25
Tera Guru

Hi All,

Kindly help me how to identify  "info" either it is starting with " { "  or  "[ { "

example 1:
{
data: {

      info: {
          "name": "servicenow"
             }

          }

  }

   

example 2:
{
data: {

      info: [
           {
          "name":"Servicenow"
            },{
          "name":"SNOW"
            }

          ]

      }

  }



1 ACCEPTED SOLUTION

Hi @Supriya25 

You can use:

 

var obj1 = {
    data: {
        info: {
            "name": "servicenow"
        }
    }
};

//Multiple Info objects
var obj2 = {
    data: {
        info: [{
            "name": "Servicenow"
        }, {
            "name": "SNOW"
        }]
    }
}

//Check if given input is an array
Array.isArray(YOUR_ARRAY);

//Function to check if a given input is JSON
function isJsonObject(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}

gs.info(Array.isArray(obj1.data.info)); //false
gs.info(Array.isArray(obj2.data.info)); //true
gs.info(isJsonObject(obj1.data.info)); //true
gs.info(isJsonObject(obj2.data.info)); //false

If you found this helpful, please hit the thumbs-up button and mark as correct. That helps others find their solutions.

View solution in original post

11 REPLIES 11

Bert_c1
Kilo Patron

Have you tried google, searching for 'how to convert an object to an array in javascript'?  You can find an answer there. Or use javascript's '.indexOf('info: [') of indexOf('info: {'.

can we use this method ?

if(Array.isArray(data.info))

if( ! Array.isArray(data.info))

Medi C
Giga Sage

Hi @Supriya25,

 

Please use below function to get your info object. It will be always returned as an array.

function getInfo(jsonObject) {
    var info = [];
    if (jsonObject.data.info.name) {
        info.push(jsonObject.data.info);
        return info;
    }
    if (jsonObject.data.info.length > 1) {      
        return jsonObject.data.info;
    }
	return info;
}

 Example:

//One info objects
var obj1 = {
    data: {
        info: {
            "name": "servicenow"
        }
    }
};

//Multiple Info objects
var obj2 = {
    data: {
        info: [{
            "name": "Servicenow"
        }, {
            "name": "SNOW"
        }]
    }
}

//Invalid object
var obj3 = {
}

gs.info(JSON.stringify(getInfo(obj1)))
gs.info(JSON.stringify(getInfo(obj2)))
gs.info(JSON.stringify(getInfo(obj3)))

 

This would result:

1 -  [{"name":"servicenow"}]
2 - [{"name":"Servicenow"},{"name":"SNOW"}]
3 - []

 

You can then check the returned value as an array.

 


If you found this helpful, please hit the thumbs-up button and mark as correct. That helps others find their solutions.

Hi,

I don't want to parse the data.

I want to know that how to identify that Info is object or Array. ??