0

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)
1
  • Point of education: There is no thing as a JSON object. Once you parse the data you have a JavaScript object or an array. Commented Jun 13, 2016 at 20:22

3 Answers 3

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

I added only 1 object to question, but the JSON contains more than 10 objects and I need to log the name property for all of them...
0

There are multiple name properties for each element, so I think you want to map twice:

elements.map(function(elt) {
    return !elt.evars ? [] : elt.evars.map(function(evar) {
        return evar.name;
    });
});

This will give you an array of arrays; the outer array is the elements, each of which contains an array of the names. For your example, this will be:

[
    ["Tracking Code", "Custom eVar 1"]
]

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.