nodejs - 如何在JSON字符串中循环键入&计算器

时间:2018-03-09 20:26:12

标签: json node.js loops parsing

我正在尝试制作一个小的nodejs股票代码来计算市值。大约有1500个条目。我想循环遍历它们,并总结这些值。目前停留在循环

JSON网址

https://api.coinmarketcap.com/v1/ticker/?limit=10

当前代码

const https = require("https");
const url =
  "https://api.coinmarketcap.com/v1/ticker/";

https.get(url, res => {
  res.setEncoding("utf8");
  let body = "";
  res.on("data", data => {
    body += data;
  });
  res.on("end", () => {
    body = JSON.parse(body);

    console.log(
      `Coin: ${body[0].id} -`,
      `Marketcap: ${body[0].market_cap_usd}`
    );

   //Loop through body results, sum up body[key].market_cap_usd
   //console.log(total_sum)
  });
});

当前输出

Coin: bitcoin - Marketcap: 149563018605

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

reduce是你的朋友:

const https = require("https");
const url =
  "https://api.coinmarketcap.com/v1/ticker/";

https.get(url, res => {
  res.setEncoding("utf8");
  let body = "";
  res.on("data", data => {
    body += data;
  });
  res.on("end", () => {
    body = JSON.parse(body);

    console.log(
      `Coin: ${body[0].id} -`,
      `Marketcap: ${body[0].market_cap_usd}`
    );

    const total_sum = body.reduce((sum, item) => sum + Number(item.market_cap_usd), 0)
    console.log(total_sum)
  });
});