gpt4 book ai didi

javascript - 在nodeJS中解析Coinmarketcap JSON数组

转载 作者:行者123 更新时间:2023-12-03 04:12:19 25 4
gpt4 key购买 nike

我正在开发一个网站来显示一些加密货币。一些 其中我从 Coinmarkepcap API ( https://api.coinmarketcap.com/v1/ticker/ ) 获得。

我使用的nodeJS代码如下:

var https = require('https'); 

var optionsget = {
host : 'api.coinmarketcap.com',
port : 443,
path : '/v1/ticker/bitcoin',
method : 'GET'
};

var reqGet = https.request(optionsget, function(res) {

res.on('data', function(d) {
info = JSON.parse(d);
console.log(info);
});
});

reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});

API 返回以下数据:

[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "2256.82",
"price_btc": "1.0",
...
"last_updated": "1496168353"
},
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH",
"rank": "2",
"price_usd": "204.307",
"price_btc": "0.0902657",
...
"last_updated": "1496168366"
},

我收到以下错误:

SyntaxError: Unexpected token < in JSON at position 0

我注意到 API 的结果使用了括号 [],其中包含 JSON。

如何解析 JSON 数组,以便检索每种硬币的名称、价格、ID 等?

最佳答案

您必须替换:

var optionsget = {
host : 'api.coinmarketcap.com',
port : 443,
path : '/v1/ticker/bitcoin',
method : 'GET'
};

作者:

var optionsget = {
host : 'api.coinmarketcap.com',
port : 443,
path : '/v1/ticker/bitcoin/',
method : 'GET'
};

如果您不包含尾部斜杠,网站会将您重定向到带有尾部斜杠的 URL,并且 https.request 不会透明地处理重定向。

您应该检查回调中的 HTTP 状态代码 ( check the docs ):

var reqGet = https.request(optionsget, function(res) {
res.on('data', function(d) {
if(res.statusCode == 200) {
info = JSON.parse(d);
console.log(info);
} else {
/* Do something else */
console.log("!", res.statusCode);
}
});
});

关于javascript - 在nodeJS中解析Coinmarketcap JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44267963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com