Ways to extract parameter values from a json request

Looking to utilize the bing maps API for obtaining travel time and distance between two GPS coordinates. Despite receiving a JSON response, I'm encountering difficulty extracting the values from this dictionary.

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())

This results in:

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

Now the question is how can the travelDistance (14.511) and travelDuration (21.9667) be extracted from this? Have attempted to retrieve key-value pairs without much success.

Managed to obtain keys such as:

authenticationResultCode brandLogoUri copyright resourceSets statusCode statusDescription traceId

Answer №1

If you're looking to extract data from a JSON response, consider using json.loads(). Simply pass the response content and then access values as if you were working with a dictionary:

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']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding JSON with various Tokens in C#

When I query the Klout API, I receive a response that contains the following fields: Name Score ScoreDeltas Day Change Week Change Month Change After creating classes in .NET and populating objects with JSON responses, everything functions properly. Ho ...

Every conceivable permutation of lists derived from a given list

I am seeking to generate all possible combinations of lists with a specific size. For instance, let's consider a list K, where K = [3, 5, 2]. The code snippet below accomplishes this task for the given list. However, I am interested in finding a way t ...

Python selenium is unable to interact with essential elements

PLEASE AVOID DOWNVOTING, THIS QUESTION HAS A UNIQUE APPROACH FROM THE PREVIOUS ONE, I'M UTILIZING DIFFERENT LOGIC HERE I am attempting to loop through all user reviews (represented by the "partial_entry" class) from the following page If a comment i ...

What is the optimal method for presenting data on a device from a massive database?

Currently, I am in the process of developing an iOS app that is designed to connect to a database and retrieve a JSON object containing data to be displayed in a table view asynchronously. While this approach works fine for now, I foresee potential challe ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

Removing the key from the output of FOR JSON PATH in SQL 2016: A step-by-step guide

Lately, we have incorporated the usage of FOR JSON PATH in our SQL code for various reasons. However, I am currently facing a slight issue in a specific scenario. My aim is to obtain a JSON string containing a list of OrderItemIds. Instead, what I am getti ...

Press the login button with Selenium

I'm encountering an issue with clicking on a website. I keep receiving a NoSuchElement Exception error, even though I have the correct class name from the site. What could I be overlooking? from selenium import webdriver from selenium.webdriver.commo ...

Python: Identifying the highest value across various columns in a Pandas Dataframe

I'm new to python and I have a pandas dataframe with multiple columns representing months. I want to compare these columns across a period of x months and flag any rows that have ever had a value of 2 or more. Here is the code snippet I used to gener ...

"Instead of sending JSON to the AJAX jQuery request, the PHP `json_encode` function is used

Creating a simple contact form as a WordPress plugin, I have developed a form as a popup within the same page: <form method="post" id="w_form" enctype="multipart/form-data"> <label for="first_name" class="text-secondary">First Name</la ...

selenium.common.exceptions.WebDriverException: Oops! Unable to locate the Opera binary using OperaDriver in Selenium with Python. It seems we have encountered an

I attempted to run a simple Python script that was supposed to open Google, but encountered some difficulties. After installing selenium with pip and adding the OperaDriver to my Python path as instructed on the Selenium page, I still couldn't get it ...

Leveraging the power of Jackson in Spring MVC 2.5

Apologies for the vague question, but my searches have been unfruitful. Our project uses Spring MVC 2.5, which lacks the @ResponseBody annotation. Is there a way to achieve something similar to this without it? ...

The JsonConverter and EntityData are essential components for processing and

My Azure web service is set up with a database-first EF approach. One of the entities that I have defined in Azure is as follows: public class Company : EntityData { public string CompanyName { get; set; } } This entity inherits the Id property from ...

Error when trying to access Jupyter conda API to retrieve information about two default environments for kernel specifications

After installing conda (python 3.5, channel= conda-forge) and numerous packages using conda and jupyter labextension... When I check conda info --envs only the root environment is listed even though I haven't created any additional environments) ...

A guide on customizing column names in MUI Datatables through object keys

I'm currently facing an issue where I need to set the name of a column in MUI Datatables using an object key. Specifically, I want to set one of the column names with the first element of children.childName so that it displays a list of child names, b ...

Merge together all the columns within a dataframe

Currently working on Python coding in Databricks using Spark 2.4.5. Trying to create a UDF that takes two parameters - a Dataframe and an SKid, where I need to hash all columns in that Dataframe based on the SKid. Although I have written some code for th ...

Comparing Date and Time in Rails 4 API

Hey there, I'm currently facing an issue when trying to compare datetimes using a Rails 4 JSON API. I have a scope that uses the created_at attribute: scope :later_than, -> (date) { where('created_at > ?', date) } The JSON response ...

Combining three PySpark columns into a single struct

Hello, I am a newcomer to PySpark and currently grappling with a challenge that needs solving. I have the task of merging three columns based on the values in a fourth column: Let's consider an example table layout like this: store car color cyli ...

Generating a dynamic JSON tree from a database using Java

I have a table stored in the database with the following structure and data: https://i.stack.imgur.com/Lmy9D.png I am looking to extract the JSON tree data from this table using Java: [ { "id":"null", "text":"Text1", "ch ...

What is stopping Mr. Developer from installing the necessary package dependencies for me?

I've encountered an issue with my mr.developer and buildout setup for a project. The eggs listed in my development packages' install_requires are not being installed. What could be the reason behind this? Here is the setup.py file for the projec ...

Getting Ajax response in HTML Unit can be achieved by leveraging its capability to render the HTML content of the web page

My web application responds with JSON data when I make AJAX requests to the server for CRUD operations. This is because I utilize jQuery to handle the data without needing to refresh the page (MVC). When a new entry is created in the system, the server sen ...