Home > front end >  Uncaught Type Error when accessing JSON data
Uncaught Type Error when accessing JSON data

Time:10-31

I have the following JSON data:

const randomData = 
    [
      {
        gender: 'male',
        name: {
          title: 'Mr',
          first: 'Blake',
          last: 'Li',
        },
      },
    ];

When I attempt to access the first name property using name = randomData[0].name.first, I get the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'first')

CodePudding user response:

I'm assuming you are consuming an API, that would have the following JSON structure, because your mock example are just fine to do what you want.

And prob what is happening is that some of ur data doens't have value in name object.

So you would need to make a check when trying to access name.first.

ex:

const name = randomData[0].name.first || 'No name'

const name = randomData[0].name && randomData[0].name.first

CodePudding user response:

I recommend you use a JSON validator every-time you get data to verify that structure you expect is correct. I built a small (21kBs) but powerful JSON validator: https://www.npmjs.com/package/great-json-validator

Validating the structure of incoming data will guarantee you won't get this type of errors.

  • Related