【问题标题】:Error when scraping JSON webpage JavaScript抓取 JSON 网页 JavaScript 时出错
【发布时间】:2018-03-29 18:23:26
【问题描述】:

我正在尝试抓取 JSON 网页,但它无法正常工作。不知道出了什么问题。这是我的 js/jQuery 代码:

 $.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://api.coinmarketcap.com/v1/ticker/ethereum/') + '&callback=?', function (data) {
    console.log(data.contents);
    var ethPrice = JSON.parse(data.contents).price_usd;
    alert(ethPrice)
});

我得到错误:

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success (scripts.js:6)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at HTMLScriptElement.c (jquery.min.js:4)
    at HTMLScriptElement.dispatch (jquery.min.js:3)
    at HTMLScriptElement.q.handle (jquery.min.js:3)

请帮忙。 非常感谢:)

【问题讨论】:

  • 快速说明:alert 不会向您显示对象详细信息。使用console.log
  • console.log(data.contents); 的输出是什么样的?我敢打赌第一个字符是o
  • 从您的 GET 请求中删除 &amp;callback=?
  • 你的 data.contents 是一个数组,所以你不需要解析。只需使用:data.contents[0].price_usd

标签: javascript jquery json web-scraping


【解决方案1】:

看起来你的 json 结果是一个数组 json。因此,它无法访问字段,因为它是数组。可能,你需要这个。

$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://api.coinmarketcap.com/v1/ticker/ethereum/') + '&callback=?', function (data) {
    console.log(data.contents);
    var response = JSON.parse(data.contents);
    for (var i = 0; i < response.length; i ++) {
        var ethPrice = response[i].price_usd;
        alert(ethPrice);
    }

});

【讨论】:

    【解决方案2】:
    You might also need to confirm if data has contents.
    
    $.getJSON('http://www.whateverorigin.org/get?url=' + 
    encodeURIComponent('https://api.coinmarketcap.com/v1/ticker/ethereum/') 
    + '&callback=?', function (data) {
    if (data && data.contents) {
        console.log(data.contents);
     var contents = JSON.parse(data.contents);
    //loop through contents for a price_usd attribute
    for (let i = 0; i < contents.length; i++) {
    if (contents[i].price_usd) {
    alert(contents[i].price_usd)
    }
    }
    

    } });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多