我正在尝试刮擦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)
请帮忙。非常感谢:(
看起来您的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);
}
});
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)
}
}
} }(;