簡體   English   中英

Node.js-解析從Web檢索到的json

[英]Nodejs - parsing json retrieved from web

我正在嘗試解析從網絡( https://api.coinmarketcap.com/v1/ticker/?limit=3 )中檢索到的json,並能夠選擇名稱和price_usd。 以供參考:

[
{
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "16148.3", 
    "price_btc": "1.0", 
    "24h_volume_usd": "18799600000.0", 
    "market_cap_usd": "270147332945", 
    "available_supply": "16729150.0", 
    "total_supply": "16729150.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "-0.28", 
    "percent_change_24h": "-4.64", 
    "percent_change_7d": "45.79", 
    "last_updated": "1512792553"
}, 
{
    "id": "ethereum", 
    "name": "Ethereum", 
    "symbol": "ETH", 
    "rank": "2", 
    "price_usd": "471.833", 
    "price_btc": "0.0296001", 
    "24h_volume_usd": "2170950000.0", 
    "market_cap_usd": "45401368016.0", 
    "available_supply": "96223384.0", 
    "total_supply": "96223384.0", 
    "max_supply": null, 
    "percent_change_1h": "0.01", 
    "percent_change_24h": "9.29", 
    "percent_change_7d": "0.65", 
    "last_updated": "1512792556"
}, 
{
    "id": "bitcoin-cash", 
    "name": "Bitcoin Cash", 
    "symbol": "BCH", 
    "rank": "3", 
    "price_usd": "1510.48", 
    "price_btc": "0.094759", 
    "24h_volume_usd": "2229320000.0", 
    "market_cap_usd": "25444318815.0", 
    "available_supply": "16845188.0", 
    "total_supply": "16845188.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "0.6", 
    "percent_change_24h": "1.29", 
    "percent_change_7d": "2.64", 
    "last_updated": "1512792581"
    }
]

這是我目前擁有的代碼:

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';
var dataResponse = '';
var body = '';

function retrieveData() {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() { 
            dataResponse = JSON.parse(body);
        });


    }).on('error', function(e) {
          console.log("Error: ", e);
    });

} 

retrieveData();

var temp = (dataResponse[0]);

console.log(temp);

我希望能夠得到類似的東西並能夠選擇名稱和價格:

        "id": "bitcoin", 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "rank": "1", 
        "price_usd": "16148.3", 
        "price_btc": "1.0", 
        "24h_volume_usd": "18799600000.0", 
        "market_cap_usd": "270147332945", 
        "available_supply": "16729150.0", 
        "total_supply": "16729150.0", 
        "max_supply": "21000000.0", 
        "percent_change_1h": "-0.28", 
        "percent_change_24h": "-4.64", 
        "percent_change_7d": "45.79", 
        "last_updated": "1512792553"

我得到的錯誤是它記錄了未定義的。 我不確定自己在做什么錯。 我還將如何選擇名稱? 我會把每個塊分成一個數組並通過索引選擇它們嗎?

使您的函數接受回調,像這樣

function retrieveData(callback) {
    https.get(url, function(res){
        body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() { 
            var dataResponse = JSON.parse(body);
            callback(dataResponse,null);
        });
    }).on('error', function(e) {
          console.log("Error: ", e);
            callback(null,e)
        });
} 

然后這樣稱呼它

retrieveData(function (dataResponse, err) {
 if (err) console.log(err);
 else {
   var temp = (dataResponse[0]);
   console.log(temp);
 }
});

您的問題是,函數receiveData是異步的,並且在設置dataResponse數組之前實際上已運行console.log。 關於異步代碼及其處理方法,這里有不錯的文章: 如何返回異步調用的響應?

您需要記住,在完成對URL的請求后,將執行.on.end的回調。

要訪問它,可以將函數包裝在promise中並使用.then如下所示。

承諾請查看此鏈接以更好地理解異步處理。

function retrieveData() {
  return new Promise((resolve, reject) => {
    https.get(url, function(res){
        body = '';

        res.on('data', function(chunk) {
          body += chunk;
        });

        res.on('end', function() {
          resolve(JSON.parse(body));
        });


    }).on('error', function(e) {
        reject(e);
    });
  })  
}

retrieveData().then(response => {
  console.log(response[0]);
}).catch(error => {
  console.log(error)
})

因此,我認為您已經在那里,所有您需要做的就是將“ dataResponse”記錄到控制台。 由於“ dataResponse”是對象數組,因此您可以使用簡單的javascript將對象簡單地輸出到控制台。 它是這樣的:

```

var https = require ("https")

var url = 'https://api.coinmarketcap.com/v1/ticker/?limit=3';

function retrieveData () {
    https.get (url, function (res){
        body = '';

        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function () { 
            dataResponse = JSON.parse (body);
            console.log (dataResponse[0])
        });


    }).on ('error', function (e) {
          console.log ("Error: ", e);
    });

} 

retrieveData ()

```

暫無
暫無

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

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