When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:
import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)
And the partial response is like:
[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo#zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david#sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception#century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer#century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer#century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather#century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall#century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}
Write before the print(j)
import pdb; pdb.set_trace()
Run your script and then the console will wait for commands, there you can write commands, start playing with your json, remember that a Json are tuples with dictionaries, that can have more tupels or more dictionaries inside, so you will end with something like
print (j[1]['EmailAddress'])
Finally found the solution:
import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
for item in j:
print(item['Members'][0]['FirstLastName'],item['Members'][0]['Email'], item['Members'][0]['Phone'])
Related
I am integrating Paypal in django-rest- framework. The issue is with paypal webhook response. I get a webhook json response when ever I pay some amount on paypal already created a url path in my application for the same.
Sample JSON object response:
{'event_version': '1.0', 'create_time': '2022-12-19T18:57:12.343Z', 'resource_type': 'checkout-order', 'resource_version': '2.0', 'event_type': 'CHECKOUT.ORDER.APPROVED', 'summary': 'An order has been approved by buyer', 'resource': {'update_time': '2022-12-19T18:57:02Z', 'create_time': '2022-12-19T18:56:51Z', 'purchase_units': [{'reference_id': 'default', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'payee': {'email_address': 'mailto:sb-dgfcl23459178#business.example.com', 'merchant_id': ''jkdshfhsjdfhjksfhjsfs'}, 'custom_id': 'e-book-1234', 'shipping': {'name': {'full_name': 'John Doe'}, 'address': {'address_line_1': '1 Main St', 'admin_area_2': 'San Jose', 'admin_area_1': 'CA', 'postal_code': '95131', 'country_code': 'US'}}, 'payments': {'captures': [{'id': '9HW93194EE464044X', 'status': 'COMPLETED', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'final_capture': True, 'seller_protection': {'status': 'ELIGIBLE', 'dispute_categories': ['ITEM_NOT_RECEIVED', 'UNAUTHORIZED_TRANSACTION']}, 'seller_receivable_breakdown': {'gross_amount': {'currency_code': 'USD', 'value': '10.00'}, 'paypal_fee': {'currency_code': 'USD', 'value': '0.84'}, 'net_amount': {'currency_code': 'USD', 'value': '9.16'}}, 'links': [{'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X/refund', 'rel': 'refund', 'method': 'POST'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'up', 'method': 'GET'}], 'create_time': '2022-12-19T18:57:02Z', 'update_time': '2022-12-19T18:57:02Z'}]}}], 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'self', 'method': 'GET'}], 'id': '4CV868937U646315D', 'payment_source': {'paypal': {}},
'intent': 'CAPTURE', 'payer': {'name': {'given_name': 'John', 'surname': 'Doe'},
'email_address': "adsfhjasdfhdajhk#gmail.com"
'payer_id': 'CSNQVZ49MMDA2',
'address': {'country_code': 'US'}},
'status': 'COMPLETED'},
'links': [{'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G/resend', 'rel': 'resend', 'method': 'POST'}]}
Is there any inbuilt library which can handle this response in python or database design to handle this or I need to create it myself.
I'm using the Geocodio API to find congreessional district information for a given address. Here's my code:
from geocodio import GeocodioClient
import json
client = GeocodioClient('MY API KEY')
availible_offices = ['Congress', 'State Legislature']
# offices_dict = ['cd': "Congress",'stateleg': "State Legislature"]
location = str(client.geocode("100 Renaissance Center, Detroit, MI 48243",fields=["cd", "stateleg"]))
print(location)
json.loads(location)
Here's the json it prints:
{'input': {'address_components': {'number': '100', 'street': 'Renaissance', 'suffix': 'Ctr', 'formatted_street': 'Renaissance Ctr', 'city': 'Detroit', 'state': 'MI', 'zip': '48243', 'country': 'US'}, 'formatted_address': '100 Renaissance Ctr, Detroit, MI 48243'}, 'results': [{'address_components': {'number': '100', 'street': 'Renaissance', 'suffix': 'Ctr', 'formatted_street': 'Renaissance Ctr', 'city': 'Detroit', 'county': 'Wayne County', 'state': 'MI', 'zip': '48243', 'country': 'US'}, 'formatted_address': '100 Renaissance Ctr, Detroit, MI 48243', 'location': {'lat': 42.329033, 'lng': -83.039762}, 'accuracy': 1, 'accuracy_type': 'rooftop', 'source': 'Semcog', 'fields': {'congressional_districts': [{'name': 'Congressional District 14', 'district_number': 14, 'congress_number': '117th', 'congress_years': '2021-2023', 'proportion': 1, 'current_legislators': [{'type': 'representative', 'bio': {'last_name': 'Lawrence', 'first_name': 'Brenda', 'birthday': '1954-10-18', 'gender': 'F', 'party': 'Democrat'}, 'contact': {'url': 'https://lawrence.house.gov', 'address': '2463 Rayburn House Office Building Washington DC 20515-2214', 'phone': '202-225-5802', 'contact_form': None}, 'social': {'rss_url': None, 'twitter': 'RepLawrence', 'facebook': '395759603917487', 'youtube': None, 'youtube_id': 'UCf0USy9GNigkB8O9sS1dodw'}, 'references': {'bioguide_id': 'L000581', 'thomas_id': '02252', 'opensecrets_id': 'N00034068', 'lis_id': None, 'cspan_id': '79924', 'govtrack_id': '412638', 'votesmart_id': '78851', 'ballotpedia_id': 'Brenda Lawrence (Michigan)', 'washington_post_id': None, 'icpsr_id': '21530', 'wikipedia_id': 'Brenda Lawrence'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}, {'type': 'senator', 'bio': {'last_name': 'Stabenow', 'first_name': 'Debbie', 'birthday': '1950-04-29', 'gender': 'F', 'party': 'Democrat'}, 'contact': {'url': 'https://www.stabenow.senate.gov', 'address': '731 Hart Senate Office Building Washington DC 20510', 'phone': '202-224-4822', 'contact_form': 'https://www.stabenow.senate.gov/contact'}, 'social': {'rss_url': 'http://stabenow.senate.gov/rss/?p=news', 'twitter': 'SenStabenow', 'facebook': 'SenatorStabenow', 'youtube': 'senatorstabenow', 'youtube_id': 'UCFoDKCvxSwCUfDv-4Eg4K5A'}, 'references': {'bioguide_id': 'S000770', 'thomas_id': '01531', 'opensecrets_id': 'N00004118', 'lis_id': 'S284', 'cspan_id': '45451', 'govtrack_id': '300093', 'votesmart_id': '515', 'ballotpedia_id': 'Debbie Stabenow', 'washington_post_id': None, 'icpsr_id': '29732', 'wikipedia_id': 'Debbie Stabenow'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}, {'type': 'senator', 'bio': {'last_name': 'Peters', 'first_name': 'Gary', 'birthday': '1958-12-01', 'gender': 'M', 'party': 'Democrat'}, 'contact': {'url': 'https://www.peters.senate.gov', 'address': '724 Hart Senate Office Building Washington DC 20510', 'phone': '202-224-6221', 'contact_form': 'https://www.peters.senate.gov/contact/email-gary'}, 'social': {'rss_url': None, 'twitter': 'SenGaryPeters', 'facebook': 'SenGaryPeters', 'youtube': 'RepGaryPeters', 'youtube_id': 'UC7LYNbnKSK2VZqQ98YROWHQ'}, 'references': {'bioguide_id': 'P000595', 'thomas_id': '01929', 'opensecrets_id': 'N00029277', 'lis_id': 'S380', 'cspan_id': '50199', 'govtrack_id': '412305', 'votesmart_id': '8749', 'ballotpedia_id': 'Gary Peters', 'washington_post_id': None, 'icpsr_id': '20923', 'wikipedia_id': 'Gary Peters'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}]}], 'state_legislative_districts': {'house': {'name': 'State House District 6', 'district_number': '6', 'is_upcoming_state_legislative_district': False}, 'senate': {'name': 'State Senate District 1', 'district_number': '1', 'is_upcoming_state_legislative_district': False}}}}]}
Here's the error that I get:
Traceback (most recent call last):
File "/Users/aliallam/Desktop/APCSP/Create Task/Main.py", line 13, in <module>
json.loads(location)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I want to extract certain parts of the json and print them. Why am I getting this error and how do I go about doing that?
Thanks in advance!
Use eval():
dataj = eval(location)
dataj.keys()
Output:
dict_keys(['input', 'results'])
fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
{'alias': 'sandwiches', 'title': 'Sandwiches'},
{'alias': 'salad', 'title': 'Salad'}],
'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
'display_phone': '(505) 881-5293',
'distance': 3571.724649307866,
'id': 'fork-and-fig-albuquerque',
'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
'is_closed': False,
'location': {'address1': '6904 Menaul Blvd NE',
'address2': 'Ste C',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
'state': 'NM',
'zip_code': '87110'},
'name': 'Fork & Fig',
'phone': '+15058815293',
'price': '$$',
'rating': 4.5,
'review_count': 604}
frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
{'alias': 'diners', 'title': 'Diners'},
{'alias': 'tradamerican', 'title': 'American (Traditional)'}],
'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
'display_phone': '(505) 266-0550',
'distance': 4033.6583235266075,
'id': 'frontier-restaurant-albuquerque-2',
'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
'is_closed': True,
'location': {'address1': '2400 Central Ave SE',
'address2': '',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
'state': 'NM',
'zip_code': '87106'},
'name': 'Frontier Restaurant',
'phone': '+15052660550',
'price': '$',
'rating': 4.0,
'review_count': 1369}
I have two restaurant list as above and i want to make function that returns a list of only the restaurants that are not closed by using conditional loops.
restaurants = [fork_fig, frontier_restaurant]
open_restaurants(restaurants)[0]['name'] ###I want restaurant name to be appear
Below is the code that I've been working on and cannot quite sure how I can fix this to get the value that I want to return.
def open_restaurants(restaurants):
selected = []
for i in restaurants:
if fork_fig['is_closed']:
selected = restaurants[1]
else:
selected = restaurants[0]
return selected
Continuing from the comment:
fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
{'alias': 'sandwiches', 'title': 'Sandwiches'},
{'alias': 'salad', 'title': 'Salad'}],
'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
'display_phone': '(505) 881-5293',
'distance': 3571.724649307866,
'id': 'fork-and-fig-albuquerque',
'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
'is_closed': False,
'location': {'address1': '6904 Menaul Blvd NE',
'address2': 'Ste C',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
'state': 'NM',
'zip_code': '87110'},
'name': 'Fork & Fig',
'phone': '+15058815293',
'price': '$$',
'rating': 4.5,
'review_count': 604}
frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
{'alias': 'diners', 'title': 'Diners'},
{'alias': 'tradamerican', 'title': 'American (Traditional)'}],
'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
'display_phone': '(505) 266-0550',
'distance': 4033.6583235266075,
'id': 'frontier-restaurant-albuquerque-2',
'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
'is_closed': True,
'location': {'address1': '2400 Central Ave SE',
'address2': '',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
'state': 'NM',
'zip_code': '87106'},
'name': 'Frontier Restaurant',
'phone': '+15052660550',
'price': '$',
'rating': 4.0,
'review_count': 1369}
restaurants = [fork_fig, frontier_restaurant]
def open_restaurants(restaurants):
selected = []
for i in restaurants:
if 'is_closed' in i:
if not i['is_closed']:
selected.append(i['name'])
return selected
print(open_restaurants(restaurants))
OUTPUT:
['Fork & Fig']
Shorter-version:
Using list-comprehension:
def open_restaurants(restaurants):
return [x['name'] for x in restaurants if 'is_closed' in x and not x["is_closed"]]
print(open_restaurants(restaurants))
Using get() instead of indexing:
def open_restaurants(restaurants):
return [x['name'] for x in restaurants if 'name' in x and not x.get('is_closed', True)]
print(open_restaurants(restaurants))
Use the filter function:
def open_restaurants(restaurants):
return filter(lambda r: not r['is_closed'], restaurants)
Use List Comprehension here. Its one line and easy to read
open_restaurants = [restaurant.get("name") for restaurant in restaurants if not restaurant.get("is_closed")]
Output: ["Fork & Fig"]
There is a simple way to append all your open restaurants to a new list and print their names.
You will need two loops to accomplish this.
Here is how to do it:
restaurants = [fork_fig, frontier_restaurant] # a list of restaurants
def open_restaurants(restaurants):
selected = []
for i in restaurants: # append all open restaurants to a new list
if not i['is_closed']:
selected.append(i)
return selected
my_open_restaurants = open_restaurants(restaurants) # call the function
for rest in my_open_restaurants: # print all the names
print(rest['name'])
In your example the output will be: Fork & Fig
I am trying to parse this JSON data from the setlist.fm api. I am trying to get all the song names in order from each setlist. I have looked around but none of the methods describe on the internet are working.
Here is the JSON data
{'itemsPerPage': 20,
'page': 1,
'setlist': [{'artist': {'disambiguation': '',
'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
'name': 'Coldplay',
'sortName': 'Coldplay',
'tmid': 806431,
'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
'eventDate': '15-11-2017',
'id': '33e0845d',
'info': 'Last show of the A Head Full of Dreams Tour',
'lastUpdated': '2017-11-23T14:51:05.000+0000',
'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
'name': 'Maria Callas',
'sortName': 'Callas, Maria',
'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
'name': 'O mio babbino caro',
'tape': True},
{'info': 'extended intro with Charlie '
'Chaplin speech',
'name': 'A Head Full of Dreams'},
{'name': 'Yellow'},
{'name': 'Every Teardrop Is a '
'Waterfall'},
{'name': 'The Scientist'},
{'info': 'with "Oceans" excerpt in '
'intro',
'name': 'God Put a Smile Upon Your '
'Face'},
{'info': 'with Tiësto Remix outro',
'name': 'Paradise'}]},
{'name': 'B-Stage',
'song': [{'name': 'Always in My Head'},
{'name': 'Magic'},
{'info': 'single version',
'name': 'Everglow'}]},
{'name': 'A-Stage',
'song': [{'info': 'with "Army of One" excerpt '
'in intro',
'name': 'Clocks'},
{'info': 'partial',
'name': 'Midnight'},
{'name': 'Charlie Brown'},
{'name': 'Hymn for the Weekend'},
{'info': 'with "Midnight" excerpt in '
'intro',
'name': 'Fix You'},
{'name': 'Viva la Vida'},
{'name': 'Adventure of a Lifetime'},
{'cover': {'disambiguation': '',
'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
'name': 'Soda Stereo',
'sortName': 'Soda Stereo',
'tmid': 1138263,
'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
'name': 'De música ligera'}]},
{'name': 'C-Stage',
'song': [{'info': 'extended',
'name': 'Kaleidoscope',
'tape': True},
{'info': 'acoustic',
'name': 'In My Place'},
{'name': 'Amor Argentina'}]},
{'name': 'A-Stage',
'song': [{'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
'name': 'The Chainsmokers '
'& Coldplay',
'sortName': 'Chainsmokers, '
'The & '
'Coldplay',
'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
'name': 'Something Just Like This'},
{'name': 'A Sky Full of Stars'},
{'info': 'Extended Outro; followed by '
'‘Believe In Love’ Tour '
'Conclusion Video',
'name': 'Up&Up'}]}]},
'tour': {'name': 'A Head Full of Dreams'},
'url': 'https://www.setlist.fm/setlist/coldplay/2017/estadio-ciudad-de-la-plata-la-plata-argentina-33e0845d.html',
'venue': {'city': {'coords': {'lat': -34.9313889,
'long': -57.9488889},
'country': {'code': 'AR', 'name': 'Argentina'},
'id': '3432043',
'name': 'La Plata',
'state': 'Buenos Aires',
'stateCode': '01'},
'id': '3d62153',
'name': 'Estadio Ciudad de La Plata',
'url': 'https://www.setlist.fm/venue/estadio-ciudad-de-la-plata-la-plata-argentina-3d62153.html'},
'versionId': '7b4ce6d0'},
{'artist': {'disambiguation': '',
'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
'name': 'Coldplay',
'sortName': 'Coldplay',
'tmid': 806431,
'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
'eventDate': '14-11-2017',
'id': '63e08ec7',
'info': '"Paradise", "Something Just Like This" and "De música '
'ligera" were soundchecked',
'lastUpdated': '2017-11-15T02:40:25.000+0000',
'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
'name': 'Maria Callas',
'sortName': 'Callas, Maria',
'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
'name': 'O mio babbino caro',
'tape': True},
{'info': 'extended intro with Charlie '
'Chaplin speech',
'name': 'A Head Full of Dreams'},
{'name': 'Yellow'},
{'name': 'Every Teardrop Is a '
'Waterfall'},
{'name': 'The Scientist'},
{'info': 'with "Oceans" excerpt in '
'intro',
'name': 'Birds'},
{'info': 'with Tiësto Remix outro',
'name': 'Paradise'}]},
{'name': 'B-Stage',
'song': [{'name': 'Always in My Head'},
{'name': 'Magic'},
{'info': 'single version; dedicated '
'to the Argentinian victims '
'of the New York terrorist '
'attack',
'name': 'Everglow'}]},
{'name': 'A-Stage',
'song': [{'info': 'with "Army of One" excerpt '
'in intro',
'name': 'Clocks'},
{'info': 'partial',
'name': 'Midnight'},
{'name': 'Charlie Brown'},
{'name': 'Hymn for the Weekend'},
{'info': 'with "Midnight" excerpt in '
'intro',
'name': 'Fix You'},
{'name': 'Viva la Vida'},
{'name': 'Adventure of a Lifetime'},
{'cover': {'disambiguation': '',
'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
'name': 'Soda Stereo',
'sortName': 'Soda Stereo',
'tmid': 1138263,
'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
'info': 'Coldplay debut',
'name': 'De música ligera'}]},
{'name': 'C-Stage',
'song': [{'info': 'Part 1: "The Guest House"',
'name': 'Kaleidoscope',
'tape': True},
{'info': 'acoustic; Will on lead '
'vocals',
'name': 'In My Place'},
{'info': 'song made for Argentina',
'name': 'Amor Argentina'},
{'info': 'Part 2: "Amazing Grace"',
'name': 'Kaleidoscope',
'tape': True}]},
{'name': 'A-Stage',
'song': [{'name': 'Life Is Beautiful'},
{'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
'name': 'The Chainsmokers '
'& Coldplay',
'sortName': 'Chainsmokers, '
'The & '
'Coldplay',
'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
'name': 'Something Just Like This'},
{'name': 'A Sky Full of Stars'},
{'name': 'Up&Up'}]}]},
This is part of the JSON I grabbed from the URL.
Below is the code I am trying touse:
import requests
import json
from pprint import*
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"
headers = {'x-api-key': 'API-KEY',
'Accept': 'application/json'}
r = requests.get(url, headers=headers)
data = json.loads(r.text)
#pprint(r.json())
response = data['setlist']
#pprint(response)
for item in response:
pprint(item['sets']['set']['song']['name'])
However I get this error that I cannot resolve nor find any help online with:
pprint(item['sets']['set']['song']['name'])
TypeError: list indices must be integers or slices, not str
Dictionaries (Dict) are accessed by keys.
Lists are accessed by indexes.
i.e.
# Dict get 'item'.
data = {'key': 'item'}
data['key']
# List get 'item0'.
data = ['item0', 'item1']
data[0]
# Dict with List get 'item0'.
data = {'key': ['item0', 'item1']}
data['key'][0]
Both storage types can be nested in JSON and either needs to be accessed in a
different manner.
You have nested Lists which need to be indexed through and that can be done by
a for loop.
I have no access to workable json data except for the Python incomplete object
that you show so I have not tested my code. Thus, no assurance that this
is correct. If not, it may demonstrate how to do the task.
import requests
import json
from pprint import *
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"
headers = {'x-api-key': 'API-KEY',
'Accept': 'application/json'}
r = requests.get(url, headers=headers)
data = json.loads(r.text)
result = []
for setlist_item in data['setlist']:
for set_item in setlist_item['sets']['set']:
for song_item in set_item['song']:
result += [song_item['name']]
print(result)
Each for loop is processing each list to finally get to extending the result with
each song name.
I am trying to set a flag based on the approval type "TEST" when its value equals '1' but no "-1",am using the below but running into following error
flag = 'false'
ApprovalItem = [{'by': {'username': 'lnxbuild', 'name': 'Linux Build Service Account', 'email': 'lnxbuild#localhost'}, 'type': 'VRIF', 'description': 'Verified', 'value': '1', 'grantedOn': 1376515352}, {'by': {'username': 'c_ssugas', 'name': 'name', 'email': 'c_ssugas#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '-1', 'grantedOn': 1376532352}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'CRVW', 'description': 'Code Review', 'value': '1', 'grantedOn': 1376514495}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '1', 'grantedOn': 1376514495}]
if ApprovalItem['type'] == 'TEST' and ApprovalItem['description'] == 'Developer Verified' and ApprovalItem['value'] == '1' :
flag = True
print flag
Error:-
TypeError: list indices must be integers, not str
ApprovalItem is a list of dictionaries, not a dictionary itself.
>>> ApprovalItem = [{'by': {'username': 'lnxbuild', 'name': 'Linux Build Service Account', 'email': 'lnxbuild#localhost'}, 'type': 'VRIF', 'description': 'Verified', 'value': '1', 'grantedOn': 1376515352}, {'by': {'username': 'c_ssugas', 'name': 'name', 'email': 'c_ssugas#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '-1', 'grantedOn': 1376532352}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'CRVW', 'description': 'Code Review', 'value': '1', 'grantedOn': 1376514495}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '1', 'grantedOn': 1376514495}]
>>> print type(ApprovalItem)
<type 'list'>
>>> print type(ApprovalItem[0])
<type 'dict'>
You probably want a for-loop:
>>> for d in ApprovalItem:
... if d['type'] == 'TEST' and d['description'] == 'Developer Verified' and d['value'] == '1' :
... flag = True
... print flag
...
True
You are using list to store your several dict.
You can use for, I think, to check each dict.