gpt4 book ai didi

javascript - 如何从 node.js 调用 JSON 中的数组字段

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:53 25 4
gpt4 key购买 nike

在 node.js 应用程序中,在 server.js 文件中,我尝试使用以下代码从名为 Deckofcardsapi 的外部 API 请求并打印值以进行控制台控制。

const  request = require('request');
request('https://deckofcardsapi.com/api/deck/new/draw/?count=2', function (error, response, body) {
const data = JSON.parse(body);
console.log('remaining :', data.remaining);
console.log('statusCode:', response && response.statusCode);
console.log('suit:', data.cards[suit]);
});

当我尝试 data.cards[suit] 时,出现如下错误。

console.log('suit:', data.cards[suit]);
ReferenceError: suit is not defined
at Request._callback (/Users/lokanathc/Projects/deckOfCards/server.js:48:37)
at Request.self.callback (/Users/lokanathc/Projects/deckOfCards/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/Users/lokanathc/Projects/deckOfCards/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/Users/lokanathc/Projects/deckOfCards/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)`

但是当我只使用 data.cards 时,我得到以下输出

remaining : 50
statusCode: 200
suit: [ { code: 'QC',
images:
{ png: 'https://deckofcardsapi.com/static/img/QC.png',
svg: 'https://deckofcardsapi.com/static/img/QC.svg' },
value: 'QUEEN',
image: 'https://deckofcardsapi.com/static/img/QC.png',
suit: 'CLUBS' },
{ code: '5S',
images:
{ png: 'https://deckofcardsapi.com/static/img/5S.png',
svg: 'https://deckofcardsapi.com/static/img/5S.svg' },
value: '5',
image: 'https://deckofcardsapi.com/static/img/5S.png',
suit: 'SPADES' } ]

我应该使用什么来访问 suit: 'SPADES' 的值。

这是来自 API 的以下响应。

{
"success": true,
"cards": [
{
"image": "https://deckofcardsapi.com/static/img/KH.png",
"value": "KING",
"suit": "HEARTS",
"code": "KH"
},
{
"image": "https://deckofcardsapi.com/static/img/8C.png",
"value": "8",
"suit": "CLUBS",
"code": "8C"
}
],
"deck_id":"3p40paa87x90",
"remaining": 50
}

最佳答案

你应该使用过滤方法,例如:
data.cards.filter(card => card.suit == 'SPADES');

Documentation of filter method

编辑:

如果你想访问对象数组中suit的所有值:


让 suites = data.cards.map(card => card.suit);//套件是 ['SPADES','HEARTS']

关于javascript - 如何从 node.js 调用 JSON 中的数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com