The CreatorCon Call for Content is officially open! Get started here.

Getting undefined when accessing a value in JSON String

dheeraaj
Giga Expert

I have the following JSON object:

 

gs.info('incitems is:'+data.incitems); // outputs : [object Object],[object Object]
var str = JSON.stringify(data.incitems);  //  outputs : [{"title":"Refer a Candidate"},{"title":"Search Jobs"}]

I need to get the value of title from the above object.

When i tried to access the value of title , it is giving me "undefined".

Help is appreciated.

 

Regards,

Dheeraaj

 

 

 

4 REPLIES 4

sachin_namjoshi
Kilo Patron
Kilo Patron

Use below sample code

 

var obj = {“name":"George","lastname":"Washington"};
var str =  JSON.stringify(obj);
gs.info(‘The object ’  + str);

 

Regards,

Sachin

Hi Sachin,

For example after converting the obj using stringify() , I am trying to access the name using str.name and it is giving me undefined in the output.

gs.info(str.name) --- > giving undefined.

 

Regards,

Dheeraj

DScroggins
Kilo Sage

Hello, It Iooks like you have an array of objects.

To access the title property either use a for loop on the array or access the array index manually like so:

data.incitems[0].title 

Hope this helps.

--David

Prateek kumar
Mega Sage

Try below:

var arr = [
{"title":"Refer a Candidate"},
{"title":"Search Jobs"}
];
var x='';
for(var i=0; i<arr.length; i++){
var myJSON = JSON.stringify(arr[i]);

var obj = JSON.parse(myJSON);
gs.print(obj.title);
}

Please mark my response as correct and helpful if it helped solved your question.
-Thanks