【问题标题】:nodejs JSON parsing.issuenodejs JSON解析.issue
【发布时间】:2018-05-25 15:38:20
【问题描述】:

我正在尝试解析 JSON 以获取特定行。我在谷歌上尝试了很多我能找到的不同的东西,这是我能得到的最接近的。

我想读什么:

[{
    "id": "pinkcoin", 
    "name": "PinkCoin", 
    "symbol": "PINK", 
    "rank": "321", 
    "price_usd": "0.0281999", 
    "price_btc": "0.00000165", 
    "24h_volume_usd": "195433.0", 
    "market_cap_usd": "10470475.0", 
    "available_supply": "371294750.0", 
    "total_supply": "388294750.0", 
    "max_supply": null, 
    "percent_change_1h": "5.48", 
    "percent_change_24h": "10.83", 
    "percent_change_7d": "-7.62", 
    "last_updated": "1513043947"
}]

我正在尝试从中提取“price_usd”部分...下面是我使用的代码:

var request = require('request');
request('https://api.coinmarketcap.com/v1/ticker/pinkcoin/', function (error, response, body) {
  fs.readFile(body, 'utf8', function (err, data) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }

    data = JSON.parse(data);

    bot.sendMessage({
      to: channelID,
      message: data.price_usd
    });
  });
});

但是当我触发这段代码发生时,我会在控制台中得到这个:

Error: Error: ENAMETOOLONG: name too long, open '[{
    "id": "pinkcoin",
    "name": "PinkCoin",
    "symbol": "PINK",
    "rank": "319",
    "price_usd": "0.0284066",
    "price_btc": "0.00000166",
    "24h_volume_usd": "195093.0",
    "market_cap_usd": "10547221.0",
    "available_supply": "371294750.0",
    "total_supply": "388294750.0",
    "max_supply": null,
    "percent_change_1h": "6.15",
    "percent_change_24h": "11.55",
    "percent_change_7d": "-6.97",
    "last_updated": "1513044245"
}]'

我一直在寻求解决这个问题,但我无处可去......

【问题讨论】:

    标签: json node.js parsing


    【解决方案1】:

    我不确定你为什么在那里使用fs.readFile。您正在获取 api call 的结果,即返回的整个 JSON 对象,并将其用作fs.readFilepath 参数。该 JSON 对象是一个非常长的字符串,它比文件路径允许的长度要长,因此会抛出 ENAMETOOLONG

    request 中的 body 值应该已经具有您想要的 JSON。除非您想根据 coinmarketcap API 的响应值从文件系统中读取某个文件,否则请使用 fs 删除该部分。

    编辑:另外,作为奖励,您也没有正确使用结果。它返回一个数组,其中第一个对象有你的结果。我不完全确定在什么情况下它会返回多个值。所以你会想要这个:

    bot.sendMessage({
      to: channelID,
      message: data.price_usd
    });
    

    ...看起来像这样:

    bot.sendMessage({
      to: channelID,
      message: data[0].price_usd
    });
    

    【讨论】:

      猜你喜欢
      • 2015-06-28
      • 1970-01-01
      • 2016-11-04
      • 2015-03-16
      • 2018-09-18
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多