简体   繁体   English

尝试访问 object 内部的嵌套 json object

[英]Trying to access a nested json object inside of an object

I've been going at this for a couple hours and I'm about at my wits end.我已经为此工作了几个小时,但我已经不知所措了。

The data I'm trying to access can either be parsed or stringified, whichever would be easier to code.我试图访问的数据可以被解析或字符串化,以更容易编码为准。 Here is the parsed version of the object that I'm trying to access这是我试图访问的 object 的解析版本

    data: [
    {
      id: '----',
      user_id: '----',
      user_login: '----',
      user_name: '----',
      game_id: '----',
      game_name: '-----',
      type: 'live',
      title: '----',
      viewer_count: -,
      started_at: '----',
      language: 'en',
      thumbnail_url: '----',
      tag_ids: [Array],
      is_mature: false
    }
  ],
  pagination: {}
}

The problem I think i'm having is the "data:" at the beginning.我认为我遇到的问题是开头的“数据:”。

Here's the code that defines this这是定义这个的代码

request.get(currentStatus, (err,res,body) => {

        if(err){

            return console.log(err);
        }
        console.log('Status: ' + res.statusCode)
        
        var data = body

        var id = _.get(body, 'data.id');
        console.log(id)
        
    });```

I really just need to access "id" and define it as its own variable.

Thank's for any advice.

I think you can simply parse the response body to a js object, and then access its fields like:我认为您可以简单地将响应正文解析为 js object,然后访问其字段,例如:

parsed = JSON.parse(body);
id = parsed.data[0].id;

and if the data array is longer than 1 you can change the index as needed如果数据数组长于 1,您可以根据需要更改索引

You only need to place the index of the array that corresponds to the object you need to access.您只需要放置与您需要访问的 object 对应的数组的索引即可。 var id = data[0].id var id = 数据[0].id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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