簡體   English   中英

如何使用 Python 3 將 JSON 文件轉換為字典

[英]How to convert a JSON file into a dictionnary with Python 3

第一次在這里發帖。 Python 和編程的總體新手。

基本上我正在關注這個人的教程(雖然不查詢相同的 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(),使它成為一個整數,但不起作用。

如果您能提供幫助,非常感謝。

requests.get().json()的數據是一個數據列表。 您可以通過for data in json_data:循環中使用for data in json_data:來遍歷列表。 然后您可以直接訪問 dict 的“段”鍵。

#!/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文檔(他在視頻中使用的 api)指定您將獲得具有特定架構的字典。 但是,當您從http://calendar.voyages-sncf.com/cdp/api獲取數據時,它們不會返回相同的數據結構。 在他們的情況下,它是一個字典列表。

因此,每次您從不同的 api(或同一 api 中的不同端點)獲取新數據時,您都會以不同的結構獲取數據。 因此,您需要更改代碼以處理每條數據。

JSON 只是在通過網絡發送字符串后將字典、列表或其他本機(python、java 或您當時使用的任何語言的本機)更改為字符串或將其更改為字符串的標准方法。 這可能會導致問題。 特別是在 python 中, set()不能直接更改為 JSON。 它需要先更改為列表,然后更改為 JSON,然后再更改為列表,然后再更改為另一側的集合。

以下示例是從此處的 google 文檔復制而來,並進行了少量修改以使其更小且更具可讀性。

{
   "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"
}

歡迎來到 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,您可以輸出到列表、字典、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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM