在 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/