I am trying to use the bing maps api to get travel time and distance between 2 gps coordinates.
I get a json answer, however, I am not able to get the values out of 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())
gives the following result:
{
'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: how do I get the travelDistance out of this ? (14.511 in this case)
or the travelDuration ? (21.9667)
tried to get the key and value pairs, but not really getting further with this.
with some other code, I got the keys :
authenticationResultCode
brandLogoUri
copyright
resourceSets
statusCode
statusDescription
traceId
You could also use json.loads() and pass the content of your response. Then access values like you do from 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']
Related
I have this giant response and I just need the IDs in "SingleItemOffers" at the end of the response (I had to cut down a lot of the json reponse due to stack overflow):
{
"FeaturedBundle": {
"Bundle": {
"ID": "2b18d53c-6173-460e-bb72-63bbb114b182",
"DataAssetID": "441117e1-40be-42e2-3aeb-49957e5c03fd",
"CurrencyID": "85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741",
"Items": [
{
"Item": {
"ItemTypeID": "e7c63390-eda7-46e0-bb7a-a6abdacd2433",
"ItemID": "291cb44a-410d-b035-4d0b-608a92c2cd91",
"Amount": 1
},
"BasePrice": 1775,
"CurrencyID": "85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741",
"DiscountPercent": 0.33,
"DiscountedPrice": 1189,
"IsPromoItem": false
}
]
},
"BundleRemainingDurationInSeconds": 804392
},
"SkinsPanelLayout": {
"SingleItemOffers": [
"5a0cd3b5-4249-bf6f-d009-17a81532660e",
"7e44fc1b-44fa-cdda-8491-f8a5bca1cfa3",
"daa73753-4b56-9d21-d73e-f3b3f4c9b1a6",
"f7425a39-43ca-e1fe-5b2b-56a51ed479c5"
],
"SingleItemOffersRemainingDurationInSeconds": 37592
}
}
This is my code at the moment and when I print the reponse it prints the entire thing:
import requests
import json
url = "https://pd.na.a.pvp.net/store/v2/storefront/XXX"
payload={}
headers = {
'X-Riot-Entitlements-JWT': 'XXX',
'Authorization': 'XXX'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
Maybe you can try this:
response[0]["FeaturedBundle"]["Bundle"]["ID"]
you can use it specifically with a FOR loop to change the sub index and get a longer response, I hope it helps you, greetings.
How do I get the value of a dict item within a list, within a dict in Python? Please see the following code for an example of what I mean.
I use the following lines of code in Python to get data from an API.
res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()
data then returns the following Python dictionary:
{
'_links': {
'next': {
'href': null
},
'previous': {
"href": null
},
'self': {
'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/'
}
},
'count': 1,
'results': [
{
'_display': 'Maple Street 99',
'_links': {
'self': {
'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/XXXXXXXXXXXXXXXX/'
}
},
'dataset': 'bag',
'landelijk_id': 'XXXXXXXXXXXXXXXX',
'type_adres': 'Hoofdadres',
'vbo_status': 'Verblijfsobject in gebruik'
}
]
}
Using Python, how do I get the value for 'landelijk_id', represented by the twelve Xs?
This should work:
>>> data['results'][0]['landelijk_id']
"XXXXXXXXXXXXXXXX"
You can just chain those [] for each child you need to access.
I'd recommend using the jmespath package to make handling nested Dictionaries easier. https://pypi.org/project/jmespath/
import jmespath
import requests
res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()
print(jmespath.search('results[].landelijk_id', data)
I'm trying to hit my geocoding server's REST API:
[https://locator.stanford.edu/arcgis/rest/services/geocode/USA_StreetAddress/GeocodeServer] (ArcGIS Server 10.6.1)
...using the POST method (which, BTW, could use an example or two, there only seems to be this VERY brief "note" on WHEN to use POST, not HOW: https://developers.arcgis.com/rest/geocode/api-reference/geocoding-geocode-addresses.htm#ESRI_SECTION1_351DE4FD98FE44958C8194EC5A7BEF7D).
I'm trying to use requests.post(), and I think I've managed to get the token accepted, etc..., but I keep getting a 400 error.
Based upon previous experience, this means something about the formatting of the data is bad, but I've cut-&-pasted directly from the Esri support site, this test pair.
# import the requests library
import requests
# Multiple address records
addresses={
"records": [
{
"attributes": {
"OBJECTID": 1,
"Street": "380 New York St.",
"City": "Redlands",
"Region": "CA",
"ZIP": "92373"
}
},
{
"attributes": {
"OBJECTID": 2,
"Street": "1 World Way",
"City": "Los Angeles",
"Region": "CA",
"ZIP": "90045"
}
}
]
}
# Parameters
# Geocoder endpoint
URL = 'https://locator.stanford.edu/arcgis/rest/services/geocode/USA_StreetAddress/GeocodeServer/geocodeAddresses?'
# token from locator.stanford.edu/arcgis/tokens
mytoken = <GeneratedToken>
# output spatial reference id
outsrid = 4326
# output format
format = 'pjson'
# params data to be sent to api
params ={'outSR':outsrid,'f':format,'token':mytoken}
# Use POST to batch geocode
r = requests.post(url=URL, data=addresses, params=params)
print(r.json())
print(r.text)
Here's what I consistently get:
{'error': {'code': 400, 'message': 'Unable to complete operation.', 'details': []}}
I had to play around with this for longer than I'd like to admit, but the trick (I guess) is to use the correct request header and convert the raw addresses to a JSON string using json.dumps().
import requests
import json
url = 'http://sampleserver6.arcgisonline.com/arcgis/rest/services/Locators/SanDiego/GeocodeServer/geocodeAddresses'
headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
addresses = json.dumps({ 'records': [{ 'attributes': { 'OBJECTID': 1, 'SingleLine': '2920 Zoo Dr' }}] })
r = requests.post(url, headers = headers, data = { 'addresses': addresses, 'f':'json'})
print(r.text)
We can run Facebook advert using python SDK. I want to know the potential reach of target audience. Is there any command available or any other way?
To get the Reach Estimates of a targeting specification using ad account.
account = AdAccount('act_<AD_ACCOUNT_ID>')
targeting_spec = {
'geo_locations': {
'countries': ['US'],
},
'age_min': 20,
'age_max': 40,
}
params = {
'currency': 'USD',
'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
'targeting_spec': targeting_spec,
}
reach_estimate = account.get_reach_estimate(params=params)
print(reach_estimate)
Response Result
{
"data": {
"users": 186000000,
"bid_estimations": [
{
"unsupported": false,
"location": 3,
"bid_amount_min": 39,
"bid_amount_median": 80,
"bid_amount_max": 121
}
],
"estimate_ready": true
}
}
186000000 users base on mention criteria
Ad Account Reachestimate
I took a nearby location from google api and i get json, when i try to split json i receive error
{
u'status':u'OK',
u'next_page_token':u'CoQC9AAAAHepdLFIvAUuqz6y6WWasKBmq5aAOYr0Bbu97upCMy4EI1Ea5t-6S6iObZdZ5_RIB7ywocdG-lF9ian5JRuTQVGL7MwbBa_uN3EfS7XzjmlVx-IKsauiEiO-Wu3r25zk9SL3yc5d_vDGvN3VQJkA7bBiDWhkloJ4RFngjBsGVWVQOnj5glrbwVVrw9Nu6DNi70C2Wdqqy_65b_jFjJiJYTAwrlfoyl7GGpxk5Gng7QgSFdtTJII9zdfkxcj3osUzklRetjraDtgfaQgxr0KA_H5btbuXz3UT6r-dyqdj2qd1tr_0oAvFkGB9t0qFbUYSe7bDETEAwdDv7MSmmXeYHQUSEMCBruHU5pb8X4EoPbPw9ncaFLgqTTICkQyGYY-boaJ1_3X3SaeT',
u'html_attributions':[
u'Listings by Indiacom Yellow Pages'],
u'results':[
{
u'name':u'Institute for Financial Management and Research',
u'reference':u'CpQBgwAAAL5Gg4T18LzUpNTEzvKWeAH0jLBuTyC_rmxOycL3KndgQ05WVKovVhiIYhnnqeOxcX1tcWesIi0vSVwugaskyy2UnJ_BrTD5ZblXzD7nLxP9L-FOQLetRgbpA6DlNzHM6Nmcu3jtJiBAOyMQJOmgL9cot7c4y18o_3E1cJrzPJfg5hK6trq2u2lvJnD2ZxJ6IxIQC2IuHwQILkrbtUd3ke5GDBoU1sZLoPY-_kARc7lEoq2naKHtwSk',
u'geometry':{
u'location':{
u'lat':13.062882,
u'lng':80.238669
}
},
u'place_id':u'ChIJKzE7o2ZmUjoRLaCtNPjba3U',
u'vicinity':u'24,
Kothari Road,
Nungambakkam,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRoAAAApH-YJpJFjPYltZYhYTs_tIVFA7vve-LMii8XbUydZJLMXbzDNkxuCuGCk9W-nFjgUrj-JoRqJLRuurGvt1oz94osENNc8bZGLBI4Joj1w-dQSyiwqqzqDdna-u0TRkJ_8S91fF3uerww341951YB2hIQX7gFjIn5tWkkEcGwErJ9oBoU0CdKRd6b2pL3Bcp09hCYvleEfaQ',
u'width':816,
u'html_attributions':[
u'From a Google User'
],
u'height':459
}
],
u'scope':u'GOOGLE',
u'id':u'2e9a63cf7368e0f90e2a20711ac56853b7c34462',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
{
u'rating':4.2,
u'name':u'Sri Sankara Senior Secondary School',
u'reference':u'CoQBdgAAAJ-Uc78EbPnLX6adzheZMWrS9sOJ9vWTQsqZOlQza-r3qozDUrl4XxWPRdHD9K_BVP0t_FhEwQt4w42X0z01uQr7dtq5cZ7ioa9zBVIQpwOkSQhxjbjQjX05YxVqGPB9MCfEikHpFKSKIaz5mPrLDgklbhQ8clD4fm9BiWNmE_mJEhD35R4GgbVNu4J-x0Lfaw3BGhRPQEXErZf3jJJkLbHs2HWVRvP2Xg',
u'geometry':{
u'location':{
u'lat':13.009931,
u'lng':80.260746
}
},
u'place_id':u'ChIJh_fXcelnUjoRd4vKDQfY_DM',
u'vicinity':u'9/21 Vasantha Press Road,
Vasanta Press Road,
Adyar,
Landmarks are Malar Hospital/Theosophical society,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRwAAAAIrFQSUJn7JB5_GgDfEPBldHptKmARqhV-6HR5fUT-MjB6ScO7ZYz1jamqoGvTqXlbEZZjxC67BvOllBHTiRIQwKyBXoI9DhleBmrCgMTrorjeDkvIDY_8ZC0pOFZOZGGH2XdfLrH1irsWZUEa0IjFRIQaATxA2BymP1KED4vxNZfnxoUTwD5Y-4-8ZPnPrhuKofUVSztcoQ',
u'width':297,
u'html_attributions':[
],
u'height':297
}
],
u'scope':u'GOOGLE',
u'id':u'a8dc412bac3ea790260d2c7d6fe08271ae883a4e',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
{
u'rating':4.5,
u'name':u'Chettinad Vidyashram',
u'reference':u'CnRoAAAAbIG1-6ecTuOcqw5hCenhtbHlAmP-nfdw_W1vEv94fXvIyCzhHSQMn95VEtKCgbLeME6qd30uGhxmLxFwXItcls-SlC7fgXwGl2JINCLTjB1RYpYC--Gr6hS-9cT7Xq2f46-dAqnpF5n2sRa1cNJJSBIQvVLDztqmh2BmqkJER9MLZxoU3gbS1TpgVj8h5Uo71QKTTyj1CdQ',
u'geometry':{
u'location':{
u'lat':13.017083,
u'lng':80.269503
}
},
u'place_id':u'ChIJR3w9SdxnUjoRs2vfnH-ERNA',
u'vicinity':u'Rajah Annamalaipuram,
Chennai',
u'photos':[
{
u'photo_reference':u'CnRoAAAAeUHwPDKO87eeGP7Fzm7aKE3VcQd6gFebbjo2FhYRHdulLZW-XdepstzETly74Id6NMOF5lqm4BHZ56C1CRnsxmdqaxJ-rcJR2Cpq2VfJaixZmBG3C-0TTNmMuPuGsjKAldr6rWCWdDVMg8FAnWhgyRIQXYPX89XdA5fl7e5RUecRWhoU-SExDqUr-GRaYVLkb8Iq_1mf-R8',
u'width':968,
u'html_attributions':[
u'From a Google User'
],
u'height':968
}
],
u'scope':u'GOOGLE',
u'id':u'f3b774d4c11a4bd20585669d9c4ae57fc12e5652',
u'types':[
u'school',
u'establishment'
],
u'icon': u'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png'
},
Here is my python code
res = json.dumps(response)
for result in response[status][results]:
print result['status']
as json was big i put half json data only.
Error i get is ror at 1431:global name 'status' is not defined
How to split this json
When i print type(response)
type tuple
If you get a json string you want to load it into the native structure with loads and then iterate over that native structure. Looking at the json string you have it also seems as if the individual results don't have a status field. You could do something like this:
res = json.loads(response)
print res['status']
for result in res['results']:
print result