Google Apps Script : Returning "null" when trying to select a specific object in a API response but I can see it in the original response

Viewed 587

I am a relative newbie to JSON in general. I am attempting to implementing some functionality in Google Apps Scripts.

My function calls the www.goldpricez.com's API and receives back some data about gold prices around the world, and of that data I would like to return one specific value (the price of Gold in MAD) in this instance.

 function fetchGoldRates() {

 var currency = "mad";
 var unit = "gram";

 var url = 'http://goldpricez.com/api/rates/currency/' + currency + '/measure/' + unit;

 var params = {
    'method': 'GET',
    'muteHttpExceptions': true,
    'headers': {
      'X-API-KEY': '###'
    }
 };

 var response = UrlFetchApp.fetch(url,params);

 var parsedData = JSON.parse(response.getContentText());

 Logger.log(parsedData); //Works and include the data I want in the object gram_in_mad

 Logger.log(parsedData.gram_in_mad); //Returns Null

}

This is the JSON data I receive back...in a pretty print visualized format.

{
   "ounce_price_usd": "1729.54",
   "gmt_ounce_price_usd_updated": "26-05-2020 04:18:01 am",
   "ounce_price_ask": "1729.54",
   "ounce_price_bid": "1729.03",
   "ounce_price_usd_today_low": "1724.91",
   "ounce_price_usd_today_high": "1730.33",
   "usd_to_mad": "9.871449",
   "gmt_mad_updated": "26-05-2020 12:05:00 am",
   "ounce_in_mad": 17073.066,
   "gram_to_ounce_formula": 0.0321,
   "gram_in_usd": 55.518234,
   "gram_in_mad": 548.0454
}

I cannot access the individual element that I want which is gram_in_mad, and I cannot understand why. Here is the logger console of Google Apps Script showing me my log lines.

1 Answers

From your question and script,

  • If the value of This is the JSON data I receive back...in a pretty print visualized format. is the value of JSON.stringify(parsedData), parsedData.gram_in_mad returns 548.0454.

  • But if the value of This is the JSON data I receive back...in a pretty print visualized format. is the value of parsedData, I thought that in the case of response of var response = UrlFetchApp.fetch(url,params);, parsedData might be the string even when var parsedData = JSON.parse(response.getContentText()); is used.

So how about the following modification?

From:

var parsedData = JSON.parse(response.getContentText());

To:

var parsedData = JSON.parse(JSON.parse(response.getContentText()));
Related