[英]Can't call a part of an object after parsed as JSON in Google Apps Script
I'm trying to make some code that can pull from an API and pull out a piece from the response. 我正在尝试制作一些可以从API中提取代码并从响应中提取代码的代码。 My code is below. 我的代码如下。
var response = UrlFetchApp.fetch('https://[API_URL]', options);
Logger.log(response.getContentText());
var firstCall = response.getContentText();
var JsonObj = JSON.parse(firstCall);
Logger.log(firstCall['id']);
sheet.appendRow(['successfully connected to API.']);
sheet.appendRow([Logger.getLog()]);
A sample response from the API is below. 以下是来自API的示例响应。
[{"id":12345678901234567,"name":"email@email.com - someText"}]
When I try to run the first code, it completes the code, logging the above line and undefined. 当我尝试运行第一个代码时,它会完成代码,记录上一行并且未定义。 My goal is to get just the ID from the string. 我的目标是从字符串中获取ID。 Thanks for your help! 谢谢你的帮助!
You're almost there. 你快到了。 To keep it simple, do it like this: 为简单起见,请按照以下步骤操作:
function getURLFromSite(){
var response = UrlFetchApp.fetch('https://jsonplaceholder.typicode.com/users');
var JsonObj = JSON.parse(response);
Logger.log(JsonObj[1].name);
}
Here's JsonObj
is like an array which you can access using JsonObj[0]
, JsonObj[1]
and JsonObj[2]
. 这里的JsonObj
就像一个数组,您可以使用JsonObj[0]
, JsonObj[1]
和JsonObj[2]
。
To access properties like id
or name
, just use the dot notation like JsonObj[0].id
or JsonObj[1].name
. 要访问id
或name
类的属性,只需使用点表示法,例如JsonObj[0].id
或JsonObj[1].name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.