简体   繁体   中英

Google Apps Script - Cannot parse JSON

Google script running inside a Google Sheet.

Trying a very simple fetch from an API, but cannot get the response parameters as I cannot get it to parse.

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]. (line 5, file "neutrinoapi") [0.17 seconds total runtime]

The response and the json line are running fine. response.getContentText() results in

{"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"}

This is correct response as per the documentation here .

I thought maybe V8 runtime would solve it, but no. When using V8 I get this error:

SyntaxError: Unexpected token 'class' at unknown function

I'm sure it's a coding101 issue.

Just a guess. If the variable response contains an object you can try to call its properties directly:

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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