0

I am using the npm module interfaces to return network adapter details. It returns what looks like JSON formatted data. I would like to pull specific properties like "address", but am having trouble parsing the data.

Data

{
  'Ethernet 1': [
    {
      address: 'ffff::ffff:ffff:ff:ffff',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: false,
      cidr: 'ffff::ffff:ffff:ff:ffff/64',
      scopeid: 7
    },
    {
      address: '10.0.0.1',
      netmask: '255.255.255.192',
      family: 'IPv4',
      mac: '00:00:00:00:00:00',
      internal: false,
      cidr: '10.0.0.1/26'
    }
  ],
  'Loopback Pseudo-Interface 1': [
    {
      address: '::1',
      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '::1/128',
      scopeid: 0
    },
    {
      address: '127.0.0.1',
      netmask: '255.0.0.0',
      family: 'IPv4',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '127.0.0.1/8'
    }
  ]
}

I have tried to stringify/parse the data into an array, but I am not sure how to identify the first object without using the specific name ('Ethernet 1').

My Code:

const interfaces = require('interfaces');
const netinterfaces = JSON.stringify(interfaces());
const results = JSON.parse(netinterfaces);

app.get('/nettest', (req, res) => {

   const {results: {adapter:[{address}]}} =results;
   console.log(address);
   console.log(results);
   res.send(results);
})

Error:

TypeError: Cannot read properties of undefined (reading 'adapter')

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dwaine
  • 1
  • 1
  • 1
    I don't see anything named `adapter` in the data you posted. Please post the data you are trying to destructure. – possum Nov 02 '22 at 17:44
  • That is actually the problem. The results I get back have the specific name of the network adapters of the machine it is run on. In my case it is "Ethernet 1" and 'Loopback Pseudo-Interface 1'. I tried to use a generic name like "adapter", but that is not going to work. I would like a way to parse the data without needing to know the name of the adapters on the specific machine. Perhaps change the name to something I can reference like "adapter1"? – Dwaine Nov 02 '22 at 18:07
  • I don't think you using "parse the data" in a commonly understood sense. The data is parsed and it is now in a JSON object. If what you want is to form an object like you described above based on the object you have in hand, you should look at the `Object.values` and `Array.prototype.map` functions. – possum Nov 02 '22 at 18:19
  • 1
    Thanks possum. Your suggestion led me to explore how to access the Keys/Values specifically and I was able to pull out the values I needed using this: – Dwaine Nov 03 '22 at 17:07

0 Answers0