簡體   English   中英

JSON中位置0處的意外令牌u無法用於異步

[英]Unexpected token u in JSON at position 0 not working for async

我對js和node.js相當陌生,但是我設法將調用轉到了API並獲取了必要的信息。 但是,當我嘗試繼續提高擊球員ID以獲得下一個可用信息時。 我已經成功獲得了未定義的錯誤檢查,並且可以正常工作。 但是我無法遍歷,因為我試圖立即在異步函數上執行某些操作。 我現在嘗試在每次運行后使整個函數異步延遲2秒,但是它返回以下錯誤(我假設是因為未定義某些內容)

**注意:當我剛得到i = 4且p = 1的值時,該值確實存在於API數據中。 但是,當我嘗試使用此代碼從這些值開始時,會出現此錯誤。

錯誤:

Unexpected token u in JSON at position 0

這是我的代碼:

   request('API Info redacted',
       setTimeout (function (err, response, body) {

        //do stuff below
        //to get the first play of the game, set i=1 and p=0
         var i = 4;
         var p = 1;
         // ************
         var boolIn = 1;

         // parse the body as JSON
         var parsedBody = JSON.parse(body);
         var apiResults = parsedBody.apiResults;

         if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
            //sets the variables to the first batter of the next inning
            p=0;
            i = i+1; 
         }

         //below pulls the apiResults from the body of the API request
         var sportId = apiResults.sportId;
         var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
         var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
         var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
         var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
         var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
         var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
         var outDifference = (outsA - outsB);
         var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
         var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
         var baseDifference = (hitA - hitB);


         //prints the details pulled above
         res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
         ", Base Sit: " + baseDifference);

         //increases the batter call
         p = p+1;

        //below ends the setTimeout
        }, 2000));

        //ended request
    });

setTimeout不會將參數傳遞給它調用的函數,因此bodyundefined 當您將其傳遞給JSON.parse ,它將被轉換為字符串"undefined" ,這不是有效的JSON文本。

您的代碼無處顯示任何傳入(或嵌入到)程序中的JSON。 您需要先解析一些JSON,然后再嘗試對其進行解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM