簡體   English   中英

如何從 json 帖子中獲取參數值

[英]How to get parameter values out of json post

我正在嘗試使用 bing 地圖 api 來獲取 2 gps 坐標之間的旅行時間和距離。 我得到一個 json 的答案,但是,我無法從這本字典中獲取值?

import requests
import json

payload = {
    "origins": [{"latitude": 50.781869, "longitude": 4.596188}],
    "destinations": [{"latitude": 50.87650130092019, "longitude": 4.671327819416231}],
    "travelMode": "driving",
}

paramtr = {"key": "mybingAPIkey"}

r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)


print(r.json())

給出以下結果:

{
  'authenticationResultCode': 'ValidCredentials',
  'brandLogoUri': 'http: //dev.virtualearth.net/Branding/logo_powered_by.png',
  'copyright': 'Copyright © 2023 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.',
  'resourceSets': [
    {
      'estimatedTotal': 1,
      'resources': [
        {
          '__type': 'DistanceMatrix:http://schemas.microsoft.com/search/local/ws/rest/v1',
          'destinations': [
            {
              'latitude': 50.87650130092019,
              'longitude': 4.671327819416231
            }
          ],
          'origins': [
            {
              'latitude': 50.781869,
              'longitude': 4.596188
            }
          ],
          'results': [
            {
              'destinationIndex': 0,
              'originIndex': 0,
              'totalWalkDuration': 0,
              'travelDistance': 14.511,
              'travelDuration': 21.9667
            }
          ]
        }
      ]
    }
  ],
  'statusCode': 200,
  'statusDescription': 'OK',
  'traceId': '7fecad5b38b94df9acef6287488b68c9|DU0000273D|0.0.0.0|DU000005E8'
}

現在:如何從中獲取 travelDistance? (在本例中為 14.511)或 travelDuration? (21.9667)

試圖獲得鍵值對,但並沒有真正取得進一步的進展。

使用其他一些代碼,我得到了鑰匙:

authenticationResultCode brandLogoUri copyright resourceSets statusCode statusDescription traceId

您還可以使用json.loads()並傳遞您的響應內容。 然后像從字典中一樣訪問值:

r = requests.post('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix', data = json.dumps(payload), params = paramtr)    

dt = json.loads(r.content)

travelDistance = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDistance']

travelDuration = dt['resourceSets'][0]['resources'][0]['results'][0]['travelDuration']

暫無
暫無

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

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