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
Related
So I'm new to graphQL and I've been figuring out the Uniswap API, through the sandbox browser, but I'm running this program which just gets metadata on the top 100 tokens and their relative pools, but the pool one isn't working at all. I'm trying to put two conditions of if token0's hash is this and token1's hash is this, it should output the pool of those two, however if only outputs pools with the token0 hash, and just ignores the second one. I've tried using and, _and, or two where's seperated by {} or , so on so forth. This is an example I have (python btw):
class ExchangePools:
def QueryPoolDB(self, hash1, hash2):
query = """
{
pools(where: {token0: "%s"}, where: {token1:"%s"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}""" % (hash1, hash2)
return query
or in the sandbox explorer this:
{
pools(where: {token0: "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"} and: {token1:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"}, first: 1, orderBy:volumeUSD, orderDirection:desc) {
id
token0 {
id
symbol
}
token1 {
id
symbol
}
token1Price
}
}
with this output:
{
"data": {
"pools": [
{
"id": "0x4585fe77225b41b697c938b018e2ac67ac5a20c0",
"token0": {
"id": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
"symbol": "WBTC"
},
"token1": {
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"symbol": "WETH"
},
"token1Price": "14.8094450357546760737720184457113"
}
]
}
}
How can I get the API to register both statements?
I have a set of ad creatives that I retreive through the Facebook Business Python SDK. I need these specifically to retreive the outbound URL when someone clicks on the ad: AdCreative['object_story_spec']['video_data']['call_to_action']['value']['link'].
I use the following call:
adcreatives = set.get_ad_creatives(fields=[
AdCreative.Field.id,
AdCreative.Field.name,
AdCreative.Field.object_story_spec,
AdCreative.Field.effective_object_story_id ,
])
Where set is an ad set.
For some cases, the result looks like this (with actual data removed), which is expected:
<AdCreative> {
"body": "[<BODY>]",
"effective_object_story_id": "[<EFFECTIVE_OBJECT_STORY_ID>]",
"id": "[<ID>]",
"name": "[<NAME>]",
"object_story_spec": {
"instagram_actor_id": "[<INSTAGRAM_ACTOR_ID>]",
"page_id": "[<PAGE_ID>]",
"video_data": {
"call_to_action": {
"type": "[<TYPE>]",
"value": {
"link": "[<LINK>]", <== This is what I need
"link_format": "[<LINK_FORMAT>]"
}
},
"image_hash": "[<IMAGE_HASH>]",
"image_url": "[<IMAGE_URL>]",
"message": "[<MESSAGE>]",
"video_id": "[<VIDEO_ID>]"
}
}
}
While sometimes results look like this:
<AdCreative> {
"effective_object_story_id": "[<EFFECTIVE_OBJECT_STORY_ID>]",
"id": "[<ID>]",
"name": "[<NAME>]",
"object_story_spec": {
"instagram_actor_id": "[<INSTAGRAM_ACTOR_ID>]",
"page_id": "[<PAGE_ID>]"
}
}
According to this earlier question: Can't get AdCreative ObjectStorySpec this is due to the fact that the object_story_spec is not populated if it is linked to a creative, instead of created along with the creative.
However, the video_data (and as such, the link), should be saved somewhere. Is there a way to retreive this? Maybe through effective_object_story_id?
The documentation page for object_story_spec (https://developers.facebook.com/docs/marketing-api/reference/ad-creative-object-story-spec/v12.0) does not have the information I am looking for.
I have an existing worksheet with an existing NamedRange for it and I would like to call the batch_update method of the API to protect that range from being edited by anyone other than the user that makes the batch_update call.
I have seen an example on how to add protected ranges via a new range definition, but not from an existing NamedRange.
I know I need to send the addProtectedRangeResponse request. Can I define the request body with a Sheetname!NamedRange notation?
this_range = worksheet_name + "!" + nrange
batch_update_spreadsheet_request_body = {
'requests': [
{
"addProtectedRange": {
"protectedRange": {
"range": {
"name": this_range,
},
"description": "Protecting xyz",
"warningOnly": False
}
}
}
],
}
EDIT: Given #Tanaike feedback, I adapted the call to something like:
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting via gsheets_manager",
"warningOnly": False,
"requestingUserCanEdit": False
}
}
}
]
}
res2 = service.spreadsheets().batchUpdate(spreadsheetId=ssId, body=body).execute()
print(res2)
But although it lists the new protections, it still lists 5 different users (all of them) as editors. If I try to manually edit the protection added by my gsheets_manager script, it complains that the range is invalid:
Interestingly, it seems to ignore the requestUserCanEdit flag according to the returning message:
{u'spreadsheetId': u'NNNNNNNNNNNNNNNNNNNNNNNNNNNN', u'replies': [{u'addProtectedRange': {u'protectedRange': {u'requestingUserCanEdit': True, u'description': u'Protecting via gsheets_manager', u'namedRangeId': u'1793914032', u'editors': {}, u'protectedRangeId': 2012740267, u'range': {u'endColumnIndex': 1, u'sheetId': 1196959832, u'startColumnIndex': 0}}}}]}
Any ideas?
How about using namedRangeId for your situation? The flow of the sample script is as follows.
Retrieve namedRangeId using spreadsheets().get of Sheets API.
Set a protected range using namedRangeId using spreadsheets().batchUpdate of Sheets API.
Sample script:
nrange = "### name ###"
ssId = "### spreadsheetId ###"
res1 = service.spreadsheets().get(spreadsheetId=ssId, fields="namedRanges").execute()
namedRangeId = ""
for e in res1['namedRanges']:
if e['name'] == nrange:
namedRangeId = e['namedRangeId']
break
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting xyz",
"warningOnly": False
}
}
}
]
}
res2 = service.spreadsheets().batchUpdate(spreadsheetId=ssId, body=body).execute()
print(res2)
Note:
This script supposes that Sheets API can be used for your environment.
This is a simple sample script. So please modify it to your situation.
References:
ProtectedRange
Named and Protected Ranges
If this was not what you want, I'm sorry.
Edit:
In my above answer, I modified your script using your settings. If you want to protect the named range, please modify body as follows.
Modified body
body = {
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"namedRangeId": namedRangeId,
"description": "Protecting xyz",
"warningOnly": False,
"editors": {"users": ["### your email address ###"]}, # Added
}
}
}
]
}
By this, the named range can be modified by only you. I'm using such settings and I confirm that it works in my environment. But if in your situation, this didn't work, I'm sorry.
This is the portion of my code that I'm having issues with.
table_data_insert_all_request_body = {
"kind": "bigquery#tableDataInsertAllRequest",
"skipInvalidRows": True,
"ignoreUnknownValues": True,
"templateSuffix": 'suffix',
"rows": [
{
"json": {
("one"): ("two"),
("three"): ("four")
}
}
]
}
request = service.tabledata().insertAll(projectId=projectId, datasetId=datasetId, tableId=tableId, body=table_data_insert_all_request_body)
response = request.execute()
If I print response, I get the response:
{u'kind': u'bigquery#tableDataInsertAllResponse'}
I can assess the project, dataset and even the table but I cant update the values in the table. What do I need to do differently? Obviously I don't want to enter two values but I cant get anything to upload. Once I can get something to upload I'll be able to get rows working.
Even though its tough to tell without looking at your schema, I am pretty sure your json data is not correct.
Here is what I use.
Bodyfields = {
"kind": "bigquery#tableDataInsertAllRequest",
"rows": [
{
"json": {
'col_name_1': 'row 1 value 1',
'col_name_2': 'row 1 value 2'
}
},
{
"json": {
'col_name_1': 'row 2 value 1',
'col_name_2': 'row 2 value 2'
}
}
]
}
Im having more difficulty with this than I should be!
Im trying to extract postalCode from the below bing maps JSON:
{
"authenticationResultCode":"ValidCredentials",
"brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright":"Copyright © 2014 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":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
56.216052482429326,
-2.9494141659354827,
56.223777917570679,
-2.9308900340645176
],
"name":"Street, Leven, KY8 5",
"point":{
"type":"Point",
"coordinates":[
56.2199152,
-2.9401521
]
},
"address":{
"addressLine":"Street",
"adminDistrict":"Scotland",
"adminDistrict2":"Fife",
"countryRegion":"United Kingdom",
"formattedAddress":"Street, Leven, KY8 5",
"locality":"Leven",
"postalCode":"KY8 5"
},
"confidence":"Medium",
"entityType":"Address",
"geocodePoints":[
{
"type":"Point",
"coordinates":[
56.2199152,
-2.9401521
],
"calculationMethod":"Interpolation",
"usageTypes":[
"Display",
"Route"
]
}
],
"matchCodes":[
"Good"
]
}
]
}
],
"statusCode":200,
"statusDescription":"OK",
"traceId":"8fdd75362a694e02a45fa17d6e7c0e95|DB40080932|02.00.108.1000|DB4SCH010061257, DB4SCH010061346"
}
My code only returns the field names and not the attribute:
r = requests.get(current_url)
json_data = r.json()
for item in json_data['resourceSets'][0]['resources']:
for field in item['address']:
print field
What am I missing? Sorry for the novice question!
for field in item['address'] by default iterate through the key in item['address'] (a dictionary) only, so you need to:
for item in json_data['resourceSets'][0]['resources']:
for field in item['address']:
print field, item['address'][field]
For loops over dictionaries in Python iterate just over the keys. If you want the values as well, you should use .items():
for field, value in item['address'].items():
print field, value