【问题标题】:How can I access the content of this "object"?如何访问此“对象”的内容?
【发布时间】:2019-07-31 07:00:34
【问题描述】:

我现在正在尝试访问一个 api (xboxapi.com)。到目前为止它工作正常 - 我从 xbox_gamercard 的 console.log 中获得了一个对象。

{"gamertag":"my_xbox_gamertag","name":"xxx","location":"xxx","bio":"xxx"}

但如果我想通过console.log(xbox_gamercard.gamertag), 输出玩家代号,我只会得到一个“未定义”的回复。

你能帮我如何访问对象的内容吗?

var xbox = require('node-xbox')("my api key");

xbox.profile.gamercard("my xbox id", function(err, xbox_gamercard){
    if(err) {
        console.log(err)
    } else {
        console.log(xbox_gamercard);
    }
});

【问题讨论】:

  • 尝试记录console.log(typeof xbox_gamercard);。我猜它是一个字符串,你需要在访问它的属性之前解析它(JSON.parse)。
  • 您正在返回一个 API 调用,因此它必须是一个字符串。先做let data = JSON.parse(xbox_gamercard),然后再做data["gamertag"],因为数据必须是字符串,你必须解析它
  • @Nisarg thx,这就是解决方案!

标签: javascript arrays json


【解决方案1】:

使用JSON.parse将收到的字符串转换为JSON对象并访问该对象的属性

var a='{"gamertag":"my_xbox_gamertag","name":"xxx","location":"xxx","bio":"xxx"}'
var b=JSON.parse(a)
console.log(b.gamertag)

【讨论】:

  • 这里不是这样。 OP 正在返回一个字符串,他们没有在变量中。
【解决方案2】:

正如@weegee 所说,使用JSON.parse。这是一个例子:

var xbox = require('node-xbox')('my api key');

xbox.profile.gamercard('my xbox id', function(err, xbox_gamercard) {
    if (err) {
        console.log(err);
    } else {
        var obj = JSON.parse(xbox_gamercard);
        console.log(obj.gamertag);
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多