我是python和脚本编写的初学者,所以我不熟悉json的固有工作原理,但这是我遇到的问题。我编写了一个脚本,该脚本从正在读取的json文件中获取“ location”变量的值,并使用googlemaps API查找该位置所在的国家/地区。但是,由于其中一些位置是重复的,因此我不想重复一遍又一遍地检查相同的位置。我将从位置变量中检索到的所有值存储在一个列表中,然后将列表转换为一个集合以消除重复项。
我的问题是:一旦检索到国家数据(将数据存储在列表中),如何将该国家数据添加到我的原始json文件中?
例如,这些是我正在读取的json文件中的一些测试。
{"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)