samedi 12 août 2017

Python: parsing Google API JSON with if/elif/else

I'm parsing Google API JSON with Python and like a cat that mount too high on a tree, I now find myself in a difficult situation.

The code is working, the only problems are the 2 elif I'm using:

        if response_data2['status'] == 'OK':
            Googleplace_id = response_data2['result']['place_id']
            Googleid = response_data2['result']['id']
            GoogleName = response_data2['result']['name']
            for types in response_data2['result']['address_components']:
                field = types.get('types', [])
                if 'street_number' in field:
                    GoogleStreet_Number = types['long_name']
                elif 'street_number' not in field:
                    GoogleStreet_Number = None
                if 'route' in field:
                    GoogleStreet = types['long_name']
                if 'postal_code' in field:
                    GooglePostal_Code = types['long_name']
                if 'locality' in field:
                    GoogleCity = types['long_name']
                elif 'locality' not in field:
                    GoogleCity = None
                if 'administrative_area_level_1' in field:
                    GoogleArea1 = types['long_name']
                if 'administrative_area_level_2' in field:
                    GoogleArea2 = types['long_name']
                if 'country' in field:
                    GoogleCountry = types['long_name']
                if 'country' in field:
                    GoogleCountryCode = types['short_name']

My script gently fill the database but 'street_number' and 'locality' are always NULL. and this is clearly because the if/elif is not working and the script is considering just the 2 elif in those 2 cases.

How to create a loop that writes the data if the JSON element is there, else, writes a None.

Now is always writing a None where there is an else

Aucun commentaire:

Enregistrer un commentaire