Access Second Instance Of Key In Nested Dictionary In Python - python

So I'm utilizing the GMusicAPI to try to interact with Google Play Music (I'm utilizing the MobileClient view) a bit. Unfortunately it's only in Python, a language I've never used before. I'm running a search, that will search for a given artist. The problem I run into is that, some artists, the artist I want isn't the first result.
My solution around that was to just search (this search returns a dictionary) for the Top 5-10 artists and then loop through them until the name in the dictionary key matches the search query.
Here's the portion of the dictionary I'm getting back from the search. This specifically is the "artist_hits" section.
[{'artist': {'name': 'Tiƫsto', 'artistArtRef': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Agzf4r7d54azste62qh6z2q7bcy', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Ti%C3%ABsto'}}, 'type': '2'},
{'artist': {'name': 'Skrillex', 'artistArtRef': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Aqy2vtuiohb4rdrakrtbphxbdme', 'artist_bio_attribution': {'kind': 'sj#attribution', 'source_title': 'artist representative'}}, 'type': '2'},
{'artist': {'kind': 'sj#artist', 'artistId': 'Achiqpfv5ncaoobeiu6vfmf2jf4', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/Zp3xcR0sc0LDnFuYy7sY-l8ggvEmPjFK_UruOSaZk25jKIYZKDsZA382WIyXqptClH91oI7QzQ', 'aspectRatio': '1'}]}, 'type': '2'},
{'artist': {'name': 'deadmau5', 'artistArtRef': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Atngmlxlixottlthpcypidmxlu4', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Deadmau5'}}, 'type': '2'},
{'artist': {'kind': 'sj#artist', 'artistId': 'A3akm3hkaas6r4mp3nmhn2d7vom', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh4.ggpht.com/6cv48SUFmOIXMjXmgs6KCw6NViHEQ2w2YRN2hhQ6HBAcVggh9-L882bYwH5VKZ2YqloodT3rNg', 'aspectRatio': '1'}]}, 'type': '2'},
{'artist': {'kind': 'sj#artist', 'artistId': 'Aatki3zj7b6fnemq2qldpjmfg74', 'name': 'Marshmellow Overcoat', 'artistArtRef': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.ggpht.com/BfiwEzdKnrAonw4myuyPu6p7GlsAhpd3ZA4E4wQQ-rkygRikCYKRwOWTTM1y3C2oYhPkqXsq0Q', 'aspectRatio': '1'}]}, 'type': '2'},
{'artist': {'kind': 'sj#artist', 'artistId': 'Aik7qbnj6ml3i7fpya4rwxjswqq', 'name': 'Marshmellow', 'artistArtRef': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/xmuuJ_XtgD1CBq7ZBKYZdo0gp7s9oiXZeNQ1lEhDfsXIWhAv2JD3w7IyM54y5OFpw8cAOEaV2Q', 'aspectRatio': '1'}]}, 'type': '2'}]
My question is how do I access anything past the first "artist" key? I need to get the "name" and "artistId" values from it. I'm calling the first one like this.
ArtistSearch['artist_hits'][0]['artist']['name']
And that works fine. However I try to access the second instance of that key like this
ArtistSearch['artist_hits'][0]['artist'][1]['name']
And it doesn't work. Any help would be greatly appreciated.

I think what you wish is:
ArtistSearch['artist_hits'][1]['artist']['name']
# ---^---
because ArtistSearch['artist_hits'] is the list, you want the second dictionary [1] and inside it the ['artist']['name'] field

Related

How to pick up data from json objects in python?

I am trying to pick Instances in the json objects data which looks like this
[{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'ami-0ceecbb0f30a902a6', 'InstanceId': 'i-xxxxx', 'InstanceType': 't2.micro', 'KeyName': 'xxxx', 'LaunchTime': {'$date': '2022-12-17T13:07:54Z'}, 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'us-west-2b', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-zxxxxx.us-west-2.compute.internal', 'PrivateIpAddress': 'xxxxx', 'ProductCodes': [], 'PublicDnsName': 'ec2-xx-xxx-xxx.us-west-2.compute.amazonaws.com', 'PublicIpAddress': 'xxxxxx', 'State': {'Code': 16, 'Name': 'running'}, 'StateTransitionReason': '', 'SubnetId': 'subnet-xxxxx', 'VpcId': 'vpc-xxxxx', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': {'$date': '2022-12-17T13:07:55Z'}, 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-xxxx'}}], 'ClientToken': '529fc1ac-bf64-4804-b0b8-7c7778ace68c', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-35-86-111-31.us-west-2.compute.amazonaws.com', 'PublicIp': 'xxxxx'}, 'Attachment': {'AttachTime': {'$date': '2022-12-17T13:07:54Z'}, 'AttachmentId': 'eni-attach-0cac7d4af20664b23', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached', 'NetworkCardIndex': 0}, 'Description': '', 'Groups': [{'GroupName': 'launch-wizard-5', 'GroupId': 'sg-xxxxx'}], 'Ipv6Addresses': [], 'MacAddress': 'xxxxx', 'NetworkInterfaceId': 'eni-xxxxx', 'OwnerId': 'xxxx', 'PrivateDnsName': 'ip-xxxxx.us-west-2.compute.internal', 'PrivateIpAddress': 'xxx.xxx.xxx', 'PrivateIpAddresses': [{'Association': {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-xx-xx-xx-xxx.us-west-2.compute.amazonaws.com', 'PublicIp': 'xxx.xxx.xxx'}, 'Primary': True, 'PrivateDnsName': 'ip-172-31-20-187.us-west-2.compute.internal', 'PrivateIpAddress': 'xxx.xxx.xxx'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-xxxxxxx', 'VpcId': 'vpc-0b09cd4sedxxx', 'InterfaceType': 'interface'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'launch-wizard-5', 'GroupId': 'sg-0a0d1c79d8076660e'}], 'SourceDestCheck': True, 'Tags': [{'Key': 'Name', 'Value': 'MainServers'}], 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}, 'CapacityReservationSpecification': {'CapacityReservationPreference': 'open'}, 'HibernationOptions': {'Configured': False}, 'MetadataOptions': {'State': 'applied', 'HttpTokens': 'optional', 'HttpPutResponseHopLimit': 1, 'HttpEndpoint': 'enabled', 'HttpProtocolIpv6': 'disabled', 'InstanceMetadataTags': 'disabled'}, 'EnclaveOptions': {'Enabled': False}, 'PlatformDetails': 'Linux/UNIX', 'UsageOperation': 'RunInstances', 'UsageOperationUpdateTime': {'$date': '2022-12-17T13:07:54Z'}, 'PrivateDnsNameOptions': {'HostnameType': 'ip-name', 'EnableResourceNameDnsARecord': True, 'EnableResourceNameDnsAAAARecord': False}, 'MaintenanceOptions': {'AutoRecovery': 'default'}}], 'OwnerId': '76979cfxdsss11', 'ReservationId': 'r-xxxxx'}]
I tired loading data and doing
resp = json.loads(jsonfile)
reqData= resp['Instances']
But getting error
TypeError: list indices must be integers or slices, not str
Is there any way I can fix this and get the data? Help will be extremely appriciated.
It's wrapped inside a list. So simply do:
print(lst[0]["Instances"])
To select only the instances from the data, you can use the json.loads function to parse the JSON data and extract the Instances field as a list.
import json
# Parse the JSON data
data = json.loads(json_data)
# Extract the instances
instances = data['Instances']
You can then iterate over the data with something like this
for instance in instances:
instance_id = instance['InstanceId']
instance_type = instance['InstanceType']
launch_time = instance['LaunchTime']

get a part from a dictionary

i'm trying to get the pulse as an output for the given url using this code
from OTXv2 import OTXv2
from OTXv2 import IndicatorTypes
otx = OTXv2("my_key")
test=otx.get_indicator_details_full(IndicatorTypes.DOMAIN, "google.com")
and when i print test i become this output:
{'general': {'sections': ['general', 'geo', 'url_list', 'passive_dns', 'malware', 'whois', 'http_scans'], 'whois': 'http://whois.domaintools.com/google.com', 'alexa': 'http://www.alexa.com/siteinfo/google.com', 'indicator': 'google.com', 'type': 'domain', 'type_title': 'Domain', 'validation': [{'source': 'ad_network', 'message': 'Whitelisted ad network domain www-google-analytics.l.google.com', 'name': 'Whitelisted ad network domain'}, {'source': 'akamai', 'message': 'Akamai rank: #3', 'name': 'Akamai Popular Domain'}, {'source': 'alexa', 'message': 'Alexa rank: #1', 'name': 'Listed on Alexa'}, {'source': 'false_positive', 'message': 'Known False Positive', 'name': 'Known False Positive'}, {'source': 'majestic', 'message': 'Whitelisted domain google.com', 'name': 'Whitelisted domain'}, {'source': 'whitelist', 'message': 'Whitelisted domain google.com', 'name': 'Whitelisted domain'}], 'base_indicator': {'id': 12915, 'indicator': 'google.com', 'type': 'domain', 'title': '', 'description': '', 'content': '', 'access_type': 'public', 'access_reason': ''}, 'pulse_info': {'count': 0, 'pulses': [], 'references': [], 'related': {'alienvault': {'adversary': [], 'malware_families': [], 'industries': []}, 'other': {'adversary': [], 'malware_families': [], 'industries': []}}}, 'false_positive':...
i want to get only the part 'count': 0 in pulse_info
i tried using test.values() but it's like i have many dictionaries together
any idea how can i solve that?
Thank you
print(test["general"]["pulse_info"]["count"])

How to get the authors name from Google books api?

When I search for the book using this link https://www.googleapis.com/books/v1/volumes?q=9780310709626 I get the author name in the details.
However when I run my code and print items I don't see the author name. I've been trying to figure out why it doesn't show from the data but I don't see any problem with my code.
print(searchBooks("9780310709626"))
def getBooks(id):
url = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
resp = url(api + id)
data = json.load(resp)
print(data["items"])
My code output:
[{'kind': 'books#volume', 'id': 'JEP3sgEACAAJ', 'etag': '92vdEneJ83g', 'selfLink': 'https://www.googleapis.com/books/v1/volumes/JEP3sgEACAAJ', 'volumeInfo': {'title': "The Beginner's Bible", 'subtitle': 'Timeless Bible Stories', 'publisher': 'Zondervan', 'publishedDate': '2005', 'description': 'Retells familiar Bible stories from the Old and New Testaments for children to enjoy.', 'industryIdentifiers': [{'type': 'ISBN_10', 'identifier': '0310709628'}, {'type': 'ISBN_13', 'identifier': '9780310709626'}], 'readingModes': {'text': False, 'image': False}, 'pageCount': 511, 'printType': 'BOOK', 'categories': ['Juvenile Nonfiction'], 'averageRating': 4.5, 'ratingsCount': 2, 'maturityRating': 'NOT_MATURE', 'allowAnonLogging': False, 'contentVersion': 'preview-1.0.0', 'panelizationSummary': {'containsEpubBubbles': False, 'containsImageBubbles': False}, 'imageLinks': {'smallThumbnail': 'http://books.google.com/books/content?id=JEP3sgEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api', 'thumbnail': 'http://books.google.com/books/content?id=JEP3sgEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api'}, 'language': 'en', 'previewLink': 'http://books.google.com.tw/books?id=JEP3sgEACAAJ&dq=isbn:9780310709626&hl=&cd=1&source=gbs_api', 'infoLink': 'http://books.google.com.tw/books?id=JEP3sgEACAAJ&dq=isbn:9780310709626&hl=&source=gbs_api', 'canonicalVolumeLink': 'https://books.google.com/books/about/The_Beginner_s_Bible.html?hl=&id=JEP3sgEACAAJ'}, 'saleInfo': {'country': 'TW', 'saleability': 'NOT_FOR_SALE', 'isEbook': False}, 'accessInfo': {'country': 'TW', 'viewability': 'NO_PAGES', 'embeddable': False, 'publicDomain': False, 'textToSpeechPermission': 'ALLOWED', 'epub': {'isAvailable': False}, 'pdf': {'isAvailable': False}, 'webReaderLink': 'http://play.google.com/books/reader?id=JEP3sgEACAAJ&hl=&printsec=frontcover&source=gbs_api', 'accessViewStatus': 'NONE', 'quoteSharingAllowed': False}, 'searchInfo': {'textSnippet': 'Retells familiar Bible stories from the Old and New Testaments for children to enjoy.'}}, {'kind': 'books#volume', 'id': 'ZRgnzQEACAAJ', 'etag': 'RXYM4Rbwx+g', 'selfLink': 'https://www.googleapis.com/books/v1/volumes/ZRgnzQEACAAJ', 'volumeInfo': {'title': "The Beginner's Bible", 'authors': ['Catherine DeVries'], 'publishedDate': '2005', 'industryIdentifiers': [{'type': 'ISBN_10', 'identifier': '0310709628'}, {'type': 'ISBN_13', 'identifier': '9780310709626'}], 'readingModes': {'text': False, 'image': False}, 'pageCount': 511, 'printType': 'BOOK', 'averageRating': 4, 'ratingsCount': 1, 'maturityRating': 'NOT_MATURE', 'allowAnonLogging': False, 'contentVersion': 'preview-1.0.0', 'panelizationSummary': {'containsEpubBubbles': False, 'containsImageBubbles': False}, 'language': 'en', 'previewLink': 'http://books.google.com.tw/books?id=ZRgnzQEACAAJ&dq=isbn:9780310709626&hl=&cd=2&source=gbs_api', 'infoLink': 'http://books.google.com.tw/books?id=ZRgnzQEACAAJ&dq=isbn:9780310709626&hl=&source=gbs_api', 'canonicalVolumeLink': 'https://books.google.com/books/about/The_Beginner_s_Bible.html?hl=&id=ZRgnzQEACAAJ'}, 'saleInfo': {'country': 'TW', 'saleability': 'NOT_FOR_SALE', 'isEbook': False}, 'accessInfo': {'country': 'TW', 'viewability': 'NO_PAGES', 'embeddable': False, 'publicDomain': False, 'textToSpeechPermission': 'ALLOWED', 'epub': {'isAvailable': False}, 'pdf': {'isAvailable': False}, 'webReaderLink': 'http://play.google.com/books/reader?id=ZRgnzQEACAAJ&hl=&printsec=frontcover&source=gbs_api', 'accessViewStatus': 'NONE', 'quoteSharingAllowed': False}}]
With the requests library:
import requests
url = 'https://www.googleapis.com/books/v1/volumes?q=9780310709626'
resp = requests.get(url)
json = resp.json()
print(json['items'][0]['volumeInfo']['authors'])
From the response you can see that authors is an array. To reach that array you will need to do json['items'][0]['volumeInfo']['authors'].
As items is also an array, meaning that there could be multiple items in this response. You might want to write extra code to deal with that other than hard-code index=0.
Note that in this case, you probably won't know the schema of the response. You should handle unexpected behaviors. For some certain books maybe some keys are missing, json['items'] could be an empty array, or even items is not in the response at all.

Python: trouble updating metadata in Salesforce report Rest API request to get report over 2000 rows

I want to pull a report which is over 2000 rows from Salesforce via API using python. How do I update the post request to send the updated metadata with the new filters in order to get the next 2000 rows of data? Here is the code I have, but the response of the post-request has the same exact filters as before. What am I doing wrong here?
Excerpt of Code:
headers = {
'Content-type': 'application/json',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer %s' % access_token
}
parameters={}
descripion = requests.request('get', instance_url+'/services/data/v51.0/analytics/reports/00O4Q000009VEPCUA4/describe',
headers=headers, params=parameters, timeout=30).json()
orig_metadata = descripion['reportMetadata']
id_column='CUST_NAME'
last_load_num='162451'
sf_id_column = descripion['reportExtendedMetadata']['detailColumnInfo'][id_column]['label']
print(sf_id_column)
metadata = {
'reportBooleanFilter': '({}) AND {}'.format(orig_metadata['reportBooleanFilter'],
len(orig_metadata['reportFilters']) + 1),
'reportFilters': orig_metadata['reportFilters']+[{'column':id_column,
'filterType': 'fieldValue',
'isRunPageEditable': True,
'operator': 'greaterThan',
'value': last_load_num}],
'standardDateFilter':[{'column': 'CUST_CREATED_DATE','durationValue': 'CUSTOM',
'endDate': '2021-07-14','startDate': '2021-07-01'}],
'detailColumns': orig_metadata['detailColumns'][:],
'sortBy': [{'sortColumn': id_column, 'sortOrder': 'Asc'}],
}
r=requests.request('post', instance_url+'/services/data/v51.0/analytics/reports/00O4Q000009VEPCUA4',
headers=headers, params={'metadata':metadata}, timeout=30).json()
Here is what's in the original metadata:
{'aggregates': ['s!rtms__Load__c.rtms__Carrier_Quote_Total__c', 'RowCount'],
'chart': None,
'crossFilters': [],
'currency': None,
'dashboardSetting': None,
'description': None,
'detailColumns': ['CUST_NAME',
'CUST_CREATED_DATE',
'rtms__Load__c.rtms__Expected_Ship_Date2__c',
'rtms__Load__c.rtms__Load_Status__c',
'rtms__Load__c.rtms__Total_Weight__c',
'rtms__Load__c.rtms__Equipment_Type__c',
'rtms__Load__c.rtms__Origin__c',
'rtms__Load__c.rtms__Destination__c',
'rtms__Load__c.rtms__Zip3_Lane__c',
'rtms__Load__c.rtms__Zip5_Lane__c',
'rtms__Load__c.rtms__Carrier_Quote_Total__c',
'rtms__Load__c.rtms__Customer_Quote_Total__c'],
'developerName': 'Adel_Past_Shipment_Test_Pricing_Tool',
'division': None,
'folderId': '00l1U000000eXWwQAM',
'groupingsAcross': [],
'groupingsDown': [],
'hasDetailRows': True,
'hasRecordCount': True,
'historicalSnapshotDates': [],
'id': '00O4Q000009VEPCUA4',
'name': 'Adel Past Shipment Test Pricing Tool',
'presentationOptions': {'hasStackedSummaries': True},
'reportBooleanFilter': None,
'reportFilters': [{'column': 'rtms__Load__c.rtms__Customer__c',
'filterType': 'fieldValue',
'isRunPageEditable': True,
'operator': 'contains',
'value': 'adel'},
{'column': 'rtms__Load__c.rtms__Load_Status__c',
'filterType': 'fieldValue',
'isRunPageEditable': True,
'operator': 'notContain',
'value': 'cancelled'}],
'reportFormat': 'TABULAR',
'reportType': {'label': 'Loads', 'type': 'CustomEntity$rtms__Load__c'},
'scope': 'organization',
'showGrandTotal': True,
'showSubtotals': True,
'sortBy': [{'sortColumn': 'CUST_CREATED_DATE', 'sortOrder': 'Desc'}],
'standardDateFilter': {'column': 'CUST_CREATED_DATE',
'durationValue': 'CUSTOM',
'endDate': None,
'startDate': None},
'standardFilters': None,
'supportsRoleHierarchy': False,
'userOrHierarchyFilterId': None}
And here is what's in r['reportMetadata']:
{'aggregates': ['s!rtms__Load__c.rtms__Carrier_Quote_Total__c', 'RowCount'],
'chart': None,
'crossFilters': [],
'currency': None,
'dashboardSetting': None,
'description': None,
'detailColumns': ['CUST_NAME',
'CUST_CREATED_DATE',
'rtms__Load__c.rtms__Expected_Ship_Date2__c',
'rtms__Load__c.rtms__Load_Status__c',
'rtms__Load__c.rtms__Total_Weight__c',
'rtms__Load__c.rtms__Equipment_Type__c',
'rtms__Load__c.rtms__Origin__c',
'rtms__Load__c.rtms__Destination__c',
'rtms__Load__c.rtms__Zip3_Lane__c',
'rtms__Load__c.rtms__Zip5_Lane__c',
'rtms__Load__c.rtms__Carrier_Quote_Total__c',
'rtms__Load__c.rtms__Customer_Quote_Total__c'],
'developerName': 'Adel_Past_Shipment_Test_Pricing_Tool',
'division': None,
'folderId': '00l1U000000eXWwQAM',
'groupingsAcross': [],
'groupingsDown': [],
'hasDetailRows': True,
'hasRecordCount': True,
'historicalSnapshotDates': [],
'id': '00O4Q000009VEPCUA4',
'name': 'Adel Past Shipment Test Pricing Tool',
'presentationOptions': {'hasStackedSummaries': True},
'reportBooleanFilter': None,
'reportFilters': [{'column': 'rtms__Load__c.rtms__Customer__c',
'filterType': 'fieldValue',
'isRunPageEditable': True,
'operator': 'contains',
'value': 'adel'},
{'column': 'rtms__Load__c.rtms__Load_Status__c',
'filterType': 'fieldValue',
'isRunPageEditable': True,
'operator': 'notContain',
'value': 'cancelled'}],
'reportFormat': 'TABULAR',
'reportType': {'label': 'Loads', 'type': 'CustomEntity$rtms__Load__c'},
'scope': 'organization',
'showGrandTotal': True,
'showSubtotals': True,
'sortBy': [{'sortColumn': 'CUST_CREATED_DATE', 'sortOrder': 'Desc'}],
'standardDateFilter': {'column': 'CUST_CREATED_DATE',
'durationValue': 'CUSTOM',
'endDate': None,
'startDate': None},
'standardFilters': None,
'supportsRoleHierarchy': False,
'userOrHierarchyFilterId': None}
code image

How to display azure resources in tabular form python SDK

I created a ResourceManagementClient using the azure python sdk:
resource_client = ResourceManagementClient(service_credential, subscription_id)
The output produced via...
for item in resource_client.resource_groups.list():
print(item)
...is difficult to read and its not in valid json format.
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/azureMaps', 'name': 'azureMaps', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499748>, 'location': 'westus', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/speechToText', 'name': 'speechToText', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba4997f0>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/neo4j-rg', 'name': 'neo4j-rg', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499b00>, 'location': 'westus', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/things', 'name': 'things', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499a90>, 'location': 'westus', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/appInsights', 'name': 'appInsights', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499a20>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/computerVision', 'name': 'computerVision', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499c50>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/dataBricks', 'name': 'dataBricks', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499be0>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/databricks-rg-databricksDEV-v6oygdyuh3sii', 'name': 'databricks-rg-databricksDEV-v6oygdyuh3sii', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499d30>, 'location': 'westus2', 'managed_by': '/subscriptions/mySub/resourceGroups/dataBricks/providers/Microsoft.Databricks/workspaces/databricksDEV', 'tags': {}}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/cool', 'name': 'cool', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499cf8>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/wsFunctionApp', 'name': 'wsFunctionApp', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499e48>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/azureStorage', 'name': 'azureStorage', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499dd8>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/azureSQL', 'name': 'azureSQL', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499d68>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/azureFunction', 'name': 'azureFunction', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499f28>, 'location': 'westus2', 'managed_by': None, 'tags': None}
{'additional_properties': {}, 'id': '/subscriptions/mySub/resourceGroups/NetworkWatcherRG', 'name': 'NetworkWatcherRG', 'properties': <azure.mgmt.resource.resources.v2018_05_01.models.resource_group_properties_py3.ResourceGroupProperties object at 0x7f0fba499f98>, 'location': 'westus2', 'managed_by': None, 'tags': None}
Can someone help me pretty print this output into something like a display() table?
Not sure why you want this, you can print all the properties you want of the item directly.
Something like:
print(item.id)
print(item.location)
print(item.tags)
Or if you want a valid json, you could custom the properties you want like below, the output is a valid json:
import json
result = []
for item in resource_client.resource_groups.list():
additional_properties = item.additional_properties
id = item.id
location = item.location
tags = item.tags
type = item.type
row = {"additional_properties": additional_properties, "id": id, "location": location, "tags": tags, "type": type}
result.append(row)
data = json.dumps(result)
print(data)
If you want to make the output easy to read, you could use the JSON Formatter Tool.

Categories

Resources