0

I am a beginner to python and scripting so I am unfamiliar with how json innately works, but this is the problem I have. I wrote a script which took values of the "location" variable from the json file I was reading and used googlemaps API to find the country this location was in. However, as some of these locations are repeat, and I did not want to repeatedly check the same location over and over. I stored all the values retrieved from the location variable in a list, then converted the list into a set to get rid of duplicates.

My question is this: once I have retrieved the country data (I have the data stored in a list), how can I add this country data to my original json file?

For instance, these are a few of my tests from the json file I am reading.

{"login": "hi", "name": "hello", "location": "Seoul, South Korea"}
{"login": "hi", "name": "hello", "location": null}
{"login": "hi", "name": "hello", "location": "Berlin, Germany"}
{"login": "hi", "name": "hello", "location": "Pittsburgh, PA"}
{"login": "hi", "name": "hello", "location": "London"}
{"login": "hi", "name": "hello", "location": "Tokyo, Japan"}


input = codecs.open(inputFile, 'r', 'utf8')
for line in input.readlines():
    temp = json.loads(line)

    if (temp['location'] != None): #some locations are Null
        locationList.append(temp['location'])
input.close()

locationList = list(set(locationList))
print(locationList)


#getting location data, storing it in countryList variable
for uniqueLocation in locationList:
    geocodeResult = gm.geocode(uniqueLocation)[0]  #getting information about each location

    geoObject = geocodeResult['address_components']    #gettnig just the address components

    for item in geoObject:  #iterating in object
        if item['types'][0] == 'country':   #if first element of this item is country
            countryName = item['long_name'] #then retrieve long_name from this item
            countryList.append(countryName)

print(countryList)
panditmonium
  • 19
  • 2
  • 8

1 Answers1

0

Check this out:

How to append data to a json file?

Kyle DeGennaro
  • 188
  • 3
  • 12