【问题标题】:NodeJS Undefined JSON ValueNodeJS 未定义的 JSON 值
【发布时间】:2018-04-03 09:51:58
【问题描述】:

我正在尝试获取 app_data,因为它包含我需要的其他数据,例如质量,但每次我尝试记录 app_data 时都会出现未定义,记录 itemJson 工作正常吗?

代码

function getBPPrice(item, itemJson){
     console.log(itemJson);
     console.log(itemJson.app_data);
     console.log(itemJson.app_data.quality);
     console.log(Prices.response.items[item].prices[itemJson.app_data.quality][itemJson.tradable].Craftable[0].value);
}

var item = theirItems[i].market_name;
var itemJson = JSON.stringify(theirItems[i], null, 4);

getBPPrice(item, itemJson);

现在,console.log(itemJson);正如我之前所说的那样工作,但是 console.log(itemJson.app_data);只是输出未定义,所以下一个输出质量值不起作用。

Json

https://pastebin.com/cFSd6GLU

Pastebin 链接,因为它很长,app_data 也在底部附近。

编辑:

我得到错误 -

未定义 C:\Users\datpe\Desktop\d\bot.js:89 console.log(itemJson.app_data.quality); ^

TypeError:无法读取未定义的属性“质量” 在 getBPrice (C:\Users\datpe\Desktop\d\bot.js:89:32) 在 processOffer (C:\Users\datpe\Desktop\d\bot.js:136:4) 在 TradeOfferManager.manager.on (C:\Users\datpe\Desktop\d\bot.js:189:2) 在 emitOne (events.js:115:13) 在 TradeOfferManager.emit (events.js:210:7) 在 received.forEach (C:\Users\datpe\node_modules\steam-tradeoffer-manager\lib\polling.js:235:10) 在 Array.forEach (本机) 在 getOffers (C:\Users\datpe\node_modules\steam-tradeoffer-manager\lib\polling.js:219:12) 在 Helpers.checkNeededDescriptions (C:\Users\datpe\node_modules\steam-tradeoffer-manager\lib\index.js:483:4) 在 Async.map (C:\Users\datpe\node_modules\steam-tradeoffer-manager\lib\assets.js:171:4)

【问题讨论】:

  • JSON.stringify() 的第二个参数是“替换器”。如果您只是在“漂亮打印”之后没有修改,那么您需要 undefined 代替,因为它实际上最不可能匹配任何东西(因为 undefined 并不是真正的 JSON 输出)。但是你不能从一个字符串中访问一个属性,所以你这里似乎有几个概念是错误的。

标签: javascript json node.js


【解决方案1】:

目前还不是 100% 清楚您要在这里做什么,但看起来您有一个数组 theirItems 并且 theirItems 的每个成员都是您想要的对象。但是当你这样做时……

var itemJson = JSON.stringify(theirItems[i], null, 4);

itemJson 现在是一个字符串,代表你想要的对象,而不是对象本身。然后您不能访问对象的各个元素,例如:

itemJson.app_data

因为它是一个字符串,而不是实际的对象。

我认为您想要做的只是抓取对象本身并将其传递给您的函数:

var itemJson = theirItems[i]
// then pass the actual object:
getBPPrice(item, itemJson);

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2019-07-02
    相关资源
    最近更新 更多