将变量分配给节点 JS 中的 JSON 数据 [英] Assign Variables to JSON data in node JS

查看:48
本文介绍了将变量分配给节点 JS 中的 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 端点,我试图将变量分配给它,现在一个 JSON 数据是一个数组,我循环遍历它以在控制台日志中获取数据,我遇到的困难是我想要为它们分配变量.

I have an API End point that i am trying to assign variables to, now the one JSON data is an array and I Loop over it to get the data out in my console log, the difficulty i am having is that i want to assign variables to them.

这是我的代码:

const request = require('request');
    request('https://fantasy.premierleague.com/api/leagues-classic/1114549/standings/?page_new_entries=1&page_standings=1&phase=1', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  var data = body.standings.results;
  data.forEach(obj => {
    Object.entries(obj).forEach(([key, value]) => {
      console.log(`${key} ${value}`);
    });
    console.log('-------------------');
  });
  
});

这是我的 JSON 数据:

and here is my JSON data:

{
"league": {
    "id": 1114549,
    "name": "The crew",
    "created": "2020-09-11T17:36:20.083556Z",
    "closed": false,
    "max_entries": null,
    "league_type": "x",
    "scoring": "c",
    "admin_entry": 3523866,
    "start_event": 1,
    "code_privacy": "p",
    "rank": null
},
"new_entries": {
    "has_next": false,
    "page": 1,
    "results": []
},
"standings": {
    "has_next": false,
    "page": 1,
    "results": [
        {
            "id": 30771462,
            "event_total": 8,
            "player_name": "Mohammed Ismail",
            "rank": 1,
            "last_rank": 0,
            "rank_sort": 1,
            "total": 8,
            "entry": 3808290,
            "entry_name": "Moe"
        }

现在我试图在我的控制台日志中仅控制台记录积分榜.result.player_name,这样我就可以在其他地方使用它,我该怎么做

Now I am trying to console log only the standings.result.player_name in my console log so i can use it else where, how do i do that

所以我在控制台中的输出应该只是 "player_name":"Mohammed Ismail",

So my output in the console should only be "player_name": "Mohammed Ismail",

推荐答案

我不确定我是否明白这个问题,但如果您想获取所有 player_name 并将其收集在数组中例如,您可以下一步:

I'm not sure that i get the question, but in case if you want to get all player_name and collect it in array as example, You can do it next:

const request = require('request');

const url = 'https://fantasy.premierleague.com/api/leagues-classic/1114549/standings/?page_new_entries=1&page_standings=1&phase=1';

async function getStandings(url) {
  return new Promise((resolve, reject) => {
    request(
      url,
      { json: true },
      (err, res, body) => {
        if (err) {
          reject(err);
          return;
        }

        resolve(body.standings.results);
      }
    );
  });
}


(async () => {
  const data = await getStandings(url);
  // here you will receive array of stadings
  console.log('data : ', data);
})();

这篇关于将变量分配给节点 JS 中的 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆