簡體   English   中英

undefined:1 undefined ^ SyntaxError: JSON 中的意外標記 u 在 position 0

[英]undefined:1 undefined ^ SyntaxError: Unexpected token u in JSON at position 0

這是我的代碼,數據被記錄但隨后或中途發生了錯誤。

錯誤信息是

undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0
function script() {
  request('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', function(error, res, body){
    for(let i = 0; i <= body.length; i++) {
      let obj = JSON.parse(body)
      request(`https://hacker-news.firebaseio.com/v0/item/${obj[i]}.json?print=pretty`, function(error, res, body){
        let myData = JSON.parse(body);
        if(myData && myData.title && myData.score && myData.id) {
          console.log('TITLE: ', myData.title)
          console.log('UPVOTES: ', myData.score)
          console.log(`https://news.ycombinator.com/item?id=${myData.id}`)
        }
      })
    }
  })
}

您可能想要解析數據然后對其進行迭代:

function script() {
  request('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', function(error, res, body){
    let obj = JSON.parse(body)
    for(let i = 0; i < obj.length; i++) {
      request(`https://hacker-news.firebaseio.com/v0/item/${obj[i]}.json?print=pretty`, function(error, res, body){
        let myData = JSON.parse(body);
        if(myData && myData.title && myData.score && myData.id) {
          console.log('TITLE: ', myData.title)
          console.log('UPVOTES: ', myData.score)
          console.log(`https://news.ycombinator.com/item?id=${myData.id}`)
        }
      })
    }
  })
}

暫無
暫無

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

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