我被困住了。看来这应该可行,但事实并非如此。
我正在尝试访问对象的键值,但是它不起作用。我以前已经做过,并且在堆栈溢出和其他地方已经读了很多东西,但是仍然无法正常工作。
这是我的代码:
var validate = UrlFetchApp.fetch(url, options);
Logger.log('validate = ' + validate);
Logger.log("validate['response'] = " + validate["response"]);
Logger.log('validate.response = ' + validate.response);
Logger.log("validate.['done'] = " + validate["done"]);
Logger.log("validate.done = " + validate.done);
var validateObj = JSON.stringify(JSON.parse(validate));
Logger.log("validateObj = " + validateObj);
Logger.log("validateObj.response = " + validateObj.response);
Logger.log("validateObj.done = " + validateObj.done);
这是日志:
validate = {
"done": true,
"response": {
"@type": "type.googleapis.com/google.apps.script.v1.ExecutionResponse",
"result": "Invalid Full Name. Please enter a valid Full Name."
}
}
validate['response'] = undefined
validate.response = undefined
validate.['done'] = undefined
validate.done = undefined
validateObj = {"done":true,"response":{"@type":"type.googleapis.com/google.apps.script.v1.ExecutionResponse","result":"Invalid Full Name. Please enter a valid Full Name."}}
validateObj.response = undefined
validateObj.done = undefined
使用方括号表示法时,我也尝试过使用单引号和双引号。
有人可以帮我看看错误吗?
答案 0 :(得分:3)
您正在尝试从字符串访问response
和done
属性,因此您将获得undefined
。您尝试对响应执行JSON.parse
,但随后将其JSON.stringify
返回字符串,只需执行JSON.parse
并访问属性
var validateObj = JSON.parse(validate); // Now you have a deserialized object
Logger.log("validateObj = " + validateObj); // You should get "validateObj = [object Object]"
Logger.log("validateObj.response = " + validateObj.response);
Logger.log("validateObj.done = " + validateObj.done);
Logger.log("validateObj[ 'response' ] = " + validateObj[ 'response' ] );
Logger.log("validateObj[ 'done' ]= " + validateObj[ 'done' ]);