json - Python Error in extracting data from nested json
问题描述
I could not find any solution similar to my json structure in python in the forum, so asking a fresh help.
I am trying to extract the value of Latitude and Longitude from the file called geolocation.json which has the following structure
{"userId":"Geo-data","data": {"mocked":false,"timestamp":1548173963281,"coords":{"speed":0,"heading":0,"accuracy":20.20400047302246,"longitude":88.4048656,"altitude":0,"latitude":22.5757344}}}
I am trying the following code to extract the latitude and longitude of the last data from the file and pass it to googleAPI for reverse geo-coding.
import json
with open("geolocation.json") as geo_file:
geo_dict = [json.loads(line) for line in geo_file]
for geo in geo_dict:
last_loc= geo_dict[-1]
geolat= str(last_loc['latitude'])
geolong= str(last_loc['longitude'])
#geolat = format(float(geo['latitude']),'.6f')
#geolong = format(float(geo['longitude']),'.6f')
from geopy.geocoders import GoogleV3
#geolat='22.5757344'
#geolong='88.4048656'
latlong = [geolat, geolong]
val = ", ".join(latlong)
geolocator = GoogleV3(api_key='My_API_KEY')
locations = geolocator.reverse(val)
if locations:
print(locations[0].address)
The code works if I hard code the latitude and longitude instead of extracting them from file (removing entire json aspect). So the problem is in extraction.I am getting the error as--
geolat= str(last_loc['latitude'])
KeyError: 'latitude'
With my limited Python knowledge, I am stuck.
解决方案
你有一个嵌套字典。利用last_loc["data"]["coords"]
前任:
import json
last_loc = json.loads('{"userId":"Geo-data","data": {"mocked":false,"timestamp":1548173963281,"coords":{"speed":0,"heading":0,"accuracy":20.20400047302246,"longitude":88.4048656,"altitude":0,"latitude":22.5757344}}}')
geolat= str(last_loc["data"]["coords"]['latitude'])
geolong= str(last_loc["data"]["coords"]['longitude'])
print(geolat)
print(geolong)
输出:
22.5757344
88.4048656
推荐阅读
- python - 如何搜索地址集是否包含某些特定单词
- java - 试图在 java netbeans 中创建表 sql
- spring-boot - 如何从多个黄瓜测试中创建多个 json 文件
- spring - Spring Data JPA Meta JpaMetamodelMappingContext 内存消耗
- python - pip 只收集包(matplotlib)不安装它
- c++11 - 错误:无法打开主文档实体
- active-directory - Openfire 和 Spark:无法连接
- c# - 从已存在依赖 DLL 的项目中引用 DLL
- sql - 两个日期之间的周数
- php - 为什么我在 Laravel 5.5.43 中收到“找不到类 'App\Providers\Form'”错误?