简体   繁体   English

Google Apps 脚本 - 无法解析 JSON

[英]Google Apps Script - Cannot parse JSON

Google script running inside a Google Sheet.在 Google 表格中运行的 Google 脚本。

Trying a very simple fetch from an API, but cannot get the response parameters as I cannot get it to parse.尝试从 API 中进行非常简单的提取,但无法获取响应参数,因为我无法解析它。

Here's my code:这是我的代码:

function neutrinoapilookup() {
    var lookupUrl = "https://neutrinoapi.net/phone-validate?user-id=123456789justtesting123@gmail.com&api-key=k00h86sr9ayZgcs2x77Zd5FUCHLlkF86hN23mAHQOG4R4Pq2&number=1567687436"
    var response = UrlFetchApp.fetch(lookupUrl, {'muteHttpExceptions': true});
    var json = response.getContentText();
    var data = JSON.parse(json);
    console.log(data.valid);
}

Here's the error:这是错误:

Execution failed: TypeError: Cannot find function parse in object [object Object].执行失败:类型错误:在 object [对象对象] 中找不到 function 解析。 (line 5, file "neutrinoapi") [0.17 seconds total runtime] (第 5 行,文件“neutrinoapi”)[总运行时间 0.17 秒]

The response and the json line are running fine.响应和 json 线路运行良好。 response.getContentText() results in response.getContentText() 结果

{"valid":true,"country":"XXXX","country-code":"XX","prefix.network":"XXXX","international-number":"XXXXXX","location":"XXXX","local-number":"XXXXX","type":"mobile","currency-code":"XXX","international-calling-code":"XXX","is-mobile":true,"country-code3":"XXX"} {"valid":true,"country":"XXXX","country-code":"XX","prefix.network":"XXXX","international-number":"XXXXXX","location":" XXXX","local-number":"XXXXX","type":"mobile","currency-code":"XXX","international-calling-code":"XXX","is-mobile":true ,"国家代码3":"XXX"}

This is correct response as per the documentation here .根据此处的文档,这是正确的响应。

I thought maybe V8 runtime would solve it, but no.我想也许 V8 运行时会解决它,但没有。 When using V8 I get this error:使用 V8 时出现此错误:

SyntaxError: Unexpected token 'class' at unknown function SyntaxError:未知的意外令牌“类” function

I'm sure it's a coding101 issue.我确定这是一个 coding101 问题。

Just a guess.只是一个猜测。 If the variable response contains an object you can try to call its properties directly:如果变量response包含一个 object 你可以尝试直接调用它的属性:

function neutrinoapilookup() {
    var lookupUrl = "https://neutrinoapi.net/phone-validate?user-id=YOUR_USER_ID&api-key=YOUR_API_KEY&number=6495552048"        
    var response = UrlFetchApp.fetch(lookupUrl, {'muteHttpExceptions': true});
    // var json = response.getContentText(); // <--- doesn't need?
    // var data = JSON.parse(json);          // <--- doesn't need?
    console.log(response.valid);
}

If responce is a string it unlikely has the method getContentText() .如果responce是一个字符串,它不太可能有方法getContentText()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM