首先发布在这里。 Python中的新手总数&编程一般。
基本上我正在关注这个人的tutorial(不查询相同的API)关于从Python中的JSON响应中提取数据。
这是我的(非常简单的)代码:
#!/usr/bin/env python
import json
import requests
url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true'
json_data = requests.get(url).json()
json_segments = json_data['segments']
print (json_segments)
现在,而不是在JSON文件中提取标记为“Segments”的数据。我收到这个错误:
json_segments = json_data['status']
TypeError: list indices must be integers or slices, not str
所以,我尝试过int(),使它成为一个整数但不起作用。
非常感谢您的帮助。
答案 0 :(得分:1)
requests.get().json()
返回的数据是一个数据列表。您可以使用for data in json_data:
循环遍历列表。然后你可以直接访问dict的'segments'键。
#!/usr/bin/env python
import requests
url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true'
json_data = requests.get(url).json()
for data in json_data:
print(data['segments'])
关于教程代码的问题:
import urllib.parse
import requests
address = 'lhr'
main_api = 'http://maps.googleapis.com/maps/api/geocode/json?'
url = main_api + urllib.parse.urlencode({'address': address})
json_data = requests.get(url).json()
json_status = json_data['status']
print(json_status)
google geocoding api here(他在视频中使用的api)的文档指定您将获得具有特定体系结构的字典。但是,当您从http://calendar.voyages-sncf.com/cdp/api
获取数据时,它们不会返回相同的数据结构。在他们的例子中,它是一个字典列表。
因此,每次从不同的api(或同一api中的不同端点)获取新数据时,您将获得不同结构的数据。因此,您需要更改代码以处理每个数据。
JSON只是一种标准方法,用于在通过网络发送字符串后,将字典,列表或其他本机(本地为python,java或当时正在使用的语言)更改为字符串。这可能会导致问题。特别是在python中,set()
不能直接更改为JSON。它需要更改为列表然后更改为JSON,然后返回到列表然后返回到另一侧的集合。
以下示例是在google docs here中进行了微小修改的复制,以使其更小,更易读。
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
],
"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"
}
答案 1 :(得分:0)
欢迎来到SO,很高兴你选择了Python :)。
如果您是Python新手并打算使用表格,请不要犹豫,学习 pandas 。有大量关于大熊猫的文件和问题。
示例:
import pandas as pd
url = 'http://calendar.voyages-sncf.com/cdp/api/proposals/v3/outward/FRPAR/FRGNL/2017-11-01/12-HAPPY_CARD/2/fr/fr?fareCodes=HC16&onlyDirectTrains=true'
df = pd.read_json(url)
和
from pandas.io.json import json_normalize
df = pd.concat(json_normalize(df["segments"].values[i]) for i in range(len(df)))
使用pandas,你可以输出到list,dictionaries,csv,json等......
这是一个片段,它返回前3行的html表:
print(df.head(3).to_html(index=False))
结果
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>arrivalDate</th>
<th>carrierCode</th>
<th>departureDate</th>
<th>destination.cityLabel</th>
<th>destination.label</th>
<th>destination.rrcode</th>
<th>duration</th>
<th>inventory</th>
<th>onboardServices</th>
<th>origin.cityLabel</th>
<th>origin.label</th>
<th>origin.rrcode</th>
<th>physicalSpace</th>
<th>quotations.12-HAPPY_CARD.cos</th>
<th>quotations.12-HAPPY_CARD.cosLevel</th>
<th>quotations.12-HAPPY_CARD.fareCode</th>
<th>quotations.12-HAPPY_CARD.fareCondition.conditions</th>
<th>quotations.12-HAPPY_CARD.fareCondition.fareName</th>
<th>quotations.12-HAPPY_CARD.fareSequence</th>
<th>quotations.12-HAPPY_CARD.fareSpecificRule</th>
<th>quotations.12-HAPPY_CARD.passengerType</th>
<th>trainNumber</th>
<th>trainType</th>
<th>transporter</th>
<th>travelClass</th>
</tr>
</thead>
<tbody>
<tr>
<td>2017-11-01T19:46</td>
<td>SN</td>
<td>2017-11-01T16:41</td>
<td>Grenoble</td>
<td>Grenoble</td>
<td>FRGNB</td>
<td>185</td>
<td>wdi</td>
<td>[BAR, HAN, SMP]</td>
<td>Paris</td>
<td>Paris Gare de Lyon</td>
<td>FRPLY</td>
<td>B</td>
<td>BN</td>
<td>17</td>
<td>HC16</td>
<td>[Pièce d'identité à présenter à bord du train....</td>
<td>TGVmax</td>
<td>None</td>
<td>None</td>
<td>PT00AD</td>
<td>6921</td>
<td>TGD</td>
<td>tgv</td>
<td>2</td>
</tr>
<tr>
<td>2017-11-01T17:45</td>
<td>SN</td>
<td>2017-11-01T14:41</td>
<td>Grenoble</td>
<td>Grenoble</td>
<td>FRGNB</td>
<td>184</td>
<td>wdi</td>
<td>[BAR, HAN, SMP]</td>
<td>Paris</td>
<td>Paris Gare de Lyon</td>
<td>FRPLY</td>
<td>B</td>
<td>BN</td>
<td>17</td>
<td>HC16</td>
<td>[Pièce d'identité à présenter à bord du train....</td>
<td>TGVmax</td>
<td>None</td>
<td>None</td>
<td>PT00AD</td>
<td>6919</td>
<td>TGD</td>
<td>tgv</td>
<td>2</td>
</tr>
<tr>
<td>2017-11-01T10:44</td>
<td>SN</td>
<td>2017-11-01T07:41</td>
<td>Grenoble</td>
<td>Grenoble</td>
<td>FRGNB</td>
<td>183</td>
<td>wdi</td>
<td>[VEP, BAR, HAN, SMP]</td>
<td>Paris</td>
<td>Paris Gare de Lyon</td>
<td>FRPLY</td>
<td>B</td>
<td>BN</td>
<td>17</td>
<td>HC16</td>
<td>[Pièce d'identité à présenter à bord du train....</td>
<td>TGVmax</td>
<td>None</td>
<td>None</td>
<td>PT00AD</td>
<td>6905</td>
<td>TGS</td>
<td>tgv</td>
<td>2</td>
</tr>
</tbody>
</table>