0

I'm developing a website to display some cryptocurrencies. Some of these I'm getting from Coinmarkepcap API (https://api.coinmarketcap.com/v1/ticker/).

The nodeJS code I'm using is the following:

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);
});

The API returns the following data:

[
    {
        "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"
    }, 

I'm getting the following error:

SyntaxError: Unexpected token < in JSON at position 0

I noticed that the result from the API is using a bracket [] with the JSON inside.

How can I parse the JSON array so I can retrieve the name, price, id, etc for each coin?

wiwa1978
  • 2,317
  • 3
  • 31
  • 67

1 Answers1

1

You must replace:

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

by:

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

If you don't include the trailing slash, the website will redirect you to the URL with the trailing slash, and https.request doesn't handle the redirect transparently.

You should check the HTTP status code in your callback (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);
        }
    });
});
Locoluis
  • 784
  • 6
  • 8