【问题标题】:How to parse JSON in node js?如何在节点 js 中解析 JSON?
【发布时间】:2018-02-26 14:07:46
【问题描述】:

我正在使用 API 的节点包装器:https://github.com/MySportsFeeds/mysportsfeeds-node/blob/master/README.md https://www.mysportsfeeds.com/data-feeds/api-docs#

通话正常并自动保存在“/results”下

这是我的代码:

 msf.authenticate("username", "password");
    var data = msf.getData('nba', '2016-2017-regular', 'cumulative_player_stats', 'json', {
        player: 'nick-young'
    });

    request(data, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var parsedData = JSON.parse(body);
            console.log(parsedData["cumulativeplayerstats"]["playerstatsentry"][0]["stats"]["PtsPerGame"]["#text"]);
        }
    });

提前致谢

【问题讨论】:

  • JSON.parse(obj)
  • "如何在节点 js 中解析 JSON"....如果body 是实际的 JSON 文本响应,那么您已经在这样做了 JSON.parse(body)。如果您遇到问题,您应该说明实际问题是什么,以及您可能收到的任何错误消息
  • 您是否有控制台日志错误以确保您没有收到错误?你控制台日志只是 parseData 以确保它被正确解析吗?您是否控制台日志正文以确保它是您认为的那样?
  • 我将问题更新为控制台中显示的内容。 JSON 保存在结果文件夹中。那么我需要从结果文件夹中获取 JSON 吗?

标签: javascript json node.js api express


【解决方案1】:

当您使用“json”格式调用 msf.getData(联赛、赛季、提要、格式和提要的任何其他适用参数)时。它返回一个 json 对象。因此,您的 data 将是一个 json 对象。

msf.authenticate("username", "password");
var data = msf.getData('nba', '2016-2017-regular', 'cumulative_player_stats', 'json', {player: 'nick-young'});

console.log(data["cumulativeplayerstats"]["playerstatsentry"][0]["stats"]["PtsPerGame"]["#text"]);

使用 fs.readFile 读取 json 文件内容

同步

const fs = require('fs');
const json = JSON.parse(fs.readFileSync('results/cumulative_player_stats-nba-2016-2017-regular.json', 'utf8'));

异步

const fs = require('fs');

fs.readFile('results/cumulative_player_stats-nba-2016-2017-regular.json', 'utf8', (err, data) => {
  if (err) throw err;

  const json = JSON.parse(data);

  console.log(json["cumulativeplayerstats"]["playerstatsentry"][0]["stats"]["PtsPerGame"]["#text"]);
});

【讨论】:

  • 控制台在有和没有 console.log 的情况下都会这样说:文件保存为“results/cumulative_player_stats-nba-2016-2017-regular.json”。如何解析那个 JSON 文件?
  • 关于异步代码的问题。我在 const json 上遇到错误;线。我怎样才能解决这个问题?
猜你喜欢
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2019-01-14
  • 1970-01-01
  • 2016-08-03
  • 2020-08-21
相关资源
最近更新 更多