簡體   English   中英

如何從node.js調用JSON中的數組字段

[英]how to call the array fields inside JSON from node.js

在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'的值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');

過濾方法的文件

編輯:

如果要訪問對象數組中所有suit值:

let suites = data.cards.map(card => card.suit); // suites is ['SPADES','HEARTS']

要訪問cards數組內的suit值,我們需要先使用其索引來訪問該數組,然后再訪問該數組中的必填字段名稱。 這對我有用。

console.log('suit:', data.cards[0].suit);

因此,對於以下代碼,

const  request = require('request');
request('https://deckofcardsapi.com/api/deck/new/draw/?count=1', 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[0].suit);
});

輸出為:

remaining : 51
statusCode: 200
suit: HEARTS

該輸出是針對count = 1的,如果我們使用count => 1,則需要使用for循環來迭代數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM