Pavel Valeriu Pavel Valeriu - 5 months ago 8
Javascript Question

How to extract data from JSON object

I am using Google Script to fetch an url that returns me the following JSON object:

[
{
"rsid":"op-bigideas",
"site_title":"Big Ideas",
"evars":[
{
"name":"Tracking Code",
"type":"text_string",
"id":"trackingcode",
"expiration_type":"week",
"expiration_custom_days":"1",
"allocation_type":"most_recent_last"
},
{
"name":"Custom eVar 1",
"description":"",
"type":"text_string",
"enabled":false,
"id":"evar1",
"expiration_type":"visit",
"expiration_custom_days":1,
"allocation_type":"most_recent_last"
}
]
}
]


How can I extract the
name
property from
evars
using
javascript
with
Google Apps Script
?

This is the code that returns me the JSON object:

var elements = JSON.parse(UrlFetchApp.fetch(url, options));


I already tried the following but only receiving
undefined
message:

1.

for(var elem in elements) {
Logger.log(elements[elem]['evars'].name);
}


2.

for(var elem in elements) {
Logger.log(elements[elem].evars.name);
}


3.

var newData = JSON.parse(elements);
Logger.log(newData.evars.name)

Answer

If I understand you correctly, you want to get the values of the name properties. This code will log the name properties:

for (var elem in elements) {
  for (var evar in elements[elem].evars) {
    Logger.log(elements[elem].evars[evar].name);
  }
}

This will output:

"Tracking Code"
"Custom eVar 1"