javascriptnode.jsjsonsteam

Why steam web API returns undefined JSON value node js


This code does a request to Steam Web API:

const request = require("request");
request({
    url: "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json",
json: true
}, (err, responser, body) => {
    console.log(body.response['trade_offers_sent']);
});

And this is what it returns:

{
  trade_offers_sent: [
    {
      tradeofferid: '3974708687',
      accountid_other: 82613664,
      message: 'test message',
      expiration_time: 1587017229,
      trade_offer_state: 9,
      items_to_give: [Array],
      is_our_offer: true,
      time_created: 1585807629,
      time_updated: 1585807629,
      from_real_time_trade: false,
      escrow_end_date: 0,
      confirmation_method: 2
    }
  ]
}

But when I'm trying to get value of accountid_other this way:

console.log(body.response['trade_offers_sent'].accountid_other);

it returns undefined.


Solution

  • The square brackets [ ... ] within trade_offers_sent indicate that it holds an array and not just a single item (it just happens to be a single item in the array). Thus to obtain you value you are interested in you need to specify the index of the item you want or use a loop to go through it. In this case you want the first item and you can use ['trade_offers_sent'][0] to obtain it.