简体   繁体   中英

Cannot extract JSON property from object

I have this code

request(options, (error, response) => {
  const data = JSON.parse(response.body)
  //console.log( JSON.stringify(data, null, " ") );
  console.log(data);
})

Which gives me this output

{
 result: 'OK',
 data: {
   body: {
     pdpHeader: [Object],
     overview: [Object],
     hotelWelcomeRewards: [Object],
     propertyDescription: [Object],
     guestReviews: [Object],
     atAGlance: [Object],
     hotelBadge: [Object],
     unavailable: {}
  },
  common: { pointOfSale: [Object], tracking: [Object] }
  },
  transportation: { transportLocations: [ [Object], [Object], [Object] ] },
  neighborhood: { neighborhoodName: 'Manhattan' }
}

Within the actual body of this output there is this:

{4 items
"result":"OK"
"data":{2 items
    "body":{14 items
        "pdpHeader":{6 items
            "hotelId":"424023"
            "destinationId":"1506246"
            "pointOfSaleId":"HCOM_US"

I want to call out the hotelID number: 424023

I have tried the following a few other modifications to this, but cannot seem to call out the correct object

console.log(data.body.pdpHeader.hotelID)

But I get the error message

console.log(data.body.pdpHeader.hotelID);
                    ^

TypeError: Cannot read property 'pdpHeader' of undefined

You've called your const data as well, so you'll either need to destruct or call .data again, like so.

Destruct

You can destruct the propery onto your data const like so:

const { data } = JSON.parse(response.body)
// data.body.pdpHeader.hotelID

Assignment

If you don't want to destruct, call data.data as per below.

const data = JSON.parse(response.body)
// data.data.body.pdpHeader.hotelID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM