I have this request which provides me JSON syntax
request( url, function (error, response) {
console.log(JSON.parse(response.body))
This generates the following within the console:
{
query: 'Manchester Holiday Inn',
moresuggestions: 2,
suggestions: [
{ group: 'CITY_GROUP', entities: [] },
{ group: 'HOTEL_GROUP', entities: [Array] },
{ group: 'LANDMARK_GROUP', entities: [] },
{ group: 'TRANSPORT_GROUP', entities: [Array] }
]
}
within the HOTEL GROUP syntax there is some additional information:
{
"query":"Manchester Holiday Inn",
"moresuggestions":0,
"suggestions":[
{},
{
"group":"HOTEL_GROUP",
"entities":[
{
"geoId":"16071381",
"destinationId":"4234234",
"type":"HOTEL",
"caption":"Manchester Holiday Inn Hotel",
"name":"Manchester Holiday Inn Hotel"
}
]
},
I want to extract the destination ID and Hotel Name
request( url, function (error, response) {
const data = JSON.parse(response.body)
hotelName = data['suggestions[1].entities[0].name'],
hotelID = data["suggestions[1].entities[0].destinationId"]
console.log(hotelName)
console.log(hotelID)
But the output from the console shows that hotelName and hotelID are undefined. Not sure what I am doing wrong.
undefined
undefined
您可以像这样访问它
data["suggestions"][1]["entities"][0][name]
The syntax you're using to access the properties is wrong – you'll need
const hotelName = data.suggestions[1].entities[0].name
const hotelID = data.suggestions[1].entities[0].destinationId
instead.
You can also use object destructuring, like so:
const {name: hotelName, destinationId: hotelID} = data.suggestions[1].entities[0];
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.