简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM