Ad

Google Places Api Returns A String, How Do I Parse To JSON Object?

In a small webshop that I am trying to setup, I need to update the opening hours in the background with firebase functions and google place details when a user creates a shoppingcart.

I can succesfully sent a GET request with POSTMAN to retrieve the opening hours of a shop using the following instructions: https://developers.google.com/places/web-service/details

But I cannot access the response from the GET request as I usually do with JSON responses.

I tried also:response.result.opening_hours.json()

Can someone tell me what I am doing wrong?

export const mapGooglePlaces = functions.database
.ref('/shopping-carts/{shoppingCartId}/shippingManner')
.onWrite(event => {
    const shippingManner = event.data.val();

    const optionsAPI = {
        method: 'GET',
        uri: 'https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=YOUR_API_KEY',
    };

    return request(optionsAPI)
        .then(response => {
            const openingHours = response.result.opening_hours;
            console.log(openingHours);
            return;
        })
        .catch(function (err) {
            console.log(err);
        });
});
Ad

Answer

The response is not a JSON object. It is JSON formatted text and must be parsed to create an object. Modify the code as follows:

return request(optionsAPI)
    .then(response => {
        const responseObject = JSON.parse(response);
        const openingHours = responseObject.result.opening_hours;
        console.log(openingHours);
        return;
    })
    .catch(function (err) {
        console.log(err);
    });

Also, before using the opening_hours or any other property of result, you should test responseObject.status === 'OK' to confirm that a place was found and at least one result was returned.

Ad
source: stackoverflow.com
Ad