Nodejs - 解析从web检索到的json

时间:2017-12-09 04:16:31

标签: javascript json node.js

我正在尝试解析从网络(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"

我得到的错误是它记录了一个未定义的。我不确定我做错了什么。我怎么去选择这个名字呢?我会将每个块拆分成一个数组并通过索引选择它们吗?

4 个答案:

答案 0 :(得分:1)

让你的函数接受回调像这样

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

然后这样称呼它,

leagues

答案 1 :(得分:0)

您的问题是函数receiveData是异步的,并且在设置dataResponse数组之前实际运行了console.log。关于异步代码以及如何在此处理它有一个很好的写法:How do I return the response from an asynchronous call?

答案 2 :(得分:0)

您需要记住.end.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) }) 之后访问它。

PROMISES查看此链接以更好地了解异步处理。

{{1}}

答案 3 :(得分:0)

所以我认为你已经在那里,所有你需要做的就是将“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 ()

```