如何确保API对请求的响应是Google应用程序脚本中的JSON类型



我正在尝试登录到应用程序脚本中的tableau rest API,然后获取工作簿下的所有可用视图。我通过PAT进行身份验证,成功登录后,我会收到来自API的类似XML响应的响应。这是它的提取代码:

function tableauTM() {
const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
Accept: 'application/json',
payload: JSON.stringify(
{
credentials: {
personalAccessTokenName: 'Tableau', 
personalAccessTokenSecret: '<token_secret>',  
site: {
contentUrl: 'pixybi', 
},
},
}
),
};
const response = UrlFetchApp.fetch(
'https://10ay.online.tableau.com/api/3.13/auth/signin', options

);

Logger.log(response)

这是我收到的回复文本:

<?xml version='1.0' encoding='UTF-8'?><tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api https://help.tableau.com/samples/en-us/rest_api/ts-api_3_13.xsd"><credentials token="1j4LgLC1TQagsevrKPwJEw|VGo4bJwHbRQPRYxuOaeHhnsVth7nNc3e" estimatedTimeToExpiration="363:04:39"><site id="c3f66f3d-1112-4bff-a5f4-b4022e303d13" contentUrl="udacitybi"/><user id="c34bf5f6-86b8-4de6-a619-f68837bce120"/></credentials></tsResponse>

如何确保响应为JSON类型,如果不可能,如何提取token、user和siteid等字段的属性值?

我们尝试了以下代码,但它抛出了类型错误:TypeError: Cannot read property 'getChild' of null

var root = XmlService.parse(response).getRootElement().getChild('credentials').getChild('user').getAttribute('id').getValue()

您可以使用XML服务解析XML。根据您的错误消息,不存在根元素,因此您应该在调用getRootElement((之前先尝试hasRootElement(。相反,您可以尝试getDescendants((并注销其结果。

通过在headers参数下添加Headers来修复options。请参阅UrlFetch文档。基本上,我的意思见下面的headers。希望这将使您能够收到JSON

const options = {
method: 'post',
muteHttpExceptions: true,
contentType: 'application/json',
headers: { Accept: 'application/json' }, …
}

最新更新