gpt4 book ai didi

python - 使用 ijson 在 Python 中解析 GoogleMaps API Json

转载 作者:行者123 更新时间:2023-11-28 18:31:09 27 4
gpt4 key购买 nike

我正在尝试解析来自 GoogleMaps API 的 JSON 响应,以将嵌套字典中的值读取到 Pandas DataFrame 中。 JSON 响应的结构如下所示。

我正在尝试创建一个名为“address_components”的 DataFrame,其中(“types”、“short_name”、“long_name”)作为列标题,每个地址查询的相应值作为行。

我试过使用 ijson:

from ijson import items
import ijson
f = urlopen('https://maps.googleapis.com/maps/api/geocode/json?address=2022+Boren+Ave%2C+Seattle+98101')

objects = list(ijson.items(f, 'results.address_components'))

objects

输出:[]

我的问题是成功遍历嵌套的字典。

我还查看了 GoogleMaps GeoLocator API Documentation , 和 GoogleMaps JSON parsing docs . This solution seems to solve the problem, but on IOS

不帮我 Handlebars 伸进鸟巢...

    "results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}

最佳答案

你可以使用json_normalize()为此::

import requests
import json
import pandas as pd

url = 'https://maps.googleapis.com/maps/api/geocode/json?address=2022+Boren+Ave%2C+Seattle+98101'

r = requests.get(url)

if r.status_code != requests.codes.ok:
r.raise_for_status()

results = json.loads(r.text)

df = pd.io.json.json_normalize(results['results'], 'address_components')

print(df)

测试:

In [17]: pd.io.json.json_normalize(results['results'], 'address_components')
Out[17]:
long_name short_name types
0 2022 2022 [street_number]
1 Boren Avenue Boren Ave [route]
2 Belltown Belltown [neighborhood, political]
3 Seattle Seattle [locality, political]
4 King County King County [administrative_area_level_2, political]
5 Washington WA [administrative_area_level_1, political]
6 United States US [country, political]
7 98121 98121 [postal_code]

关于python - 使用 ijson 在 Python 中解析 GoogleMaps API Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197958/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com