Adam
Adam

Reputation: 35

How to parse JSON in node js?

I'm using the API's node wrapper: https://github.com/MySportsFeeds/mysportsfeeds-node/blob/master/README.md https://www.mysportsfeeds.com/data-feeds/api-docs#

The call is going through fine and automatically saving on under "/results"

Here's my code:

 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"]);
        }
    });

Thanks in advance

Upvotes: 3

Views: 182

Answers (1)

Zahidul Islam
Zahidul Islam

Reputation: 125

When you call msf.getData(league, season, feed, format, and any other applicable params for the feed) with format 'json'. It return a json object. As a result your data will be a json object.

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"]);

Read json file content using fs.readFile

Sync

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

Async

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"]);
});

Upvotes: 2

Related Questions