I'm not advanced with Python Json. I have these Json result:
{
"href": "https://api.spotify.com/v1/users/wizzler/playlists",
"items": [
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c"
},
"href": "https://api.spotify.com/v1/users/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c",
"id": "53Y8wT46QIMz5H4WQ8O22c",
"images": [],
"name": "Wizzlers Big Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzler"
},
"href": "https://api.spotify.com/v1/users/wizzler",
"id": "wizzler",
"type": "user",
"uri": "spotify:user:wizzler"
},
"public": true,
"snapshot_id": "bNLWdmhh+HDsbHzhckXeDC0uyKyg4FjPI/KEsKjAE526usnz2LxwgyBoMShVL+z+",
"tracks": {
"href": "https://api.spotify.com/v1/users/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c/tracks",
"total": 30
},
"type": "playlist",
"uri": "spotify:user:wizzler:playlist:53Y8wT46QIMz5H4WQ8O22c"
},
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju"
},
"href": "https://api.spotify.com/v1/users/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju",
"id": "1AVZz0mBuGbCEoNRQdYQju",
"images": [],
"name": "Another Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzlersmate"
},
"href": "https://api.spotify.com/v1/users/wizzlersmate",
"id": "wizzlersmate",
"type": "user",
"uri": "spotify:user:wizzlersmate"
},
"public": true,
"snapshot_id": "Y0qg/IT5T02DKpw4uQKc/9RUrqQJ07hbTKyEeDRPOo9LU0g0icBrIXwVkHfQZ/aD",
"tracks": {
"href": "https://api.spotify.com/v1/users/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju/tracks",
"total": 58
},
"type": "playlist",
"uri": "spotify:user:wizzlersmate:playlist:1AVZz0mBuGbCEoNRQdYQju"
}
],
"limit": 9,
"next": null,
"offset": 0,
"previous": null,
"total": 9
}
Now I need to extract only the Playlist ids. How to do that?
Edit:
I get the Json Data from doing:
r = requests.get(BASE_URL + 'users/' + user_id + '/playlists', headers=headers)
r = r.json()
print(r) returning me the Json Data. When I try to data = json.load(r)
I get these error! AttributeError: 'dict' object has no attribute 'read'
First, load the JSON file using the built in json library.
import json
with open('path/to/json/file.json') as f:
data = json.load(f)
Then, use a list comprehension to get only the IDs.
playlist_ids = [item['id'] for item in data['items']]
Edit: Or, if you've got your JSON parsed already, just use the list comprehension. Don't do r = r.json(), that will reset the request object to the data. Set it to some other variable, data is OK - data = r.json()
playlist_ids = [item['id'] for item in data['items']]
Edit 2: If you only want it where the owner ID is "wizzler", then add a if clause to the list comprehension.
playlist_ids = [item['id'] for item in data['items'] if item['owner']['id'] == 'wizzler']
Related
I am creating posts on my site with the Wordpress API, using Python.
Everything works well.
When I am trying to update a post, it doesn't update.
I have no idea if the problem is in my code, or maybe a setting I should change?
In this example I am trying to change a simple setting on a post with just a title. Nothing fancy.
import requests
import json
import base64
credentials = "username:password"
token = base64.b64encode(credentials.encode())
post_url = "https://www.example.com/wp-json/wp/v2/posts"
header = {"Authorization": "Basic " + token.decode('utf-8'), "Content-Type":"application/json"}
postID = "1122"
data_to_send = {"comment_status": "closed"}
json_to_send = json.dumps(data_to_send)
response = requests.post(post_url + "/" + postID , headers=header, json=json_to_send)
Here is the response. The "modified" time is correct (and is also reflected in the site admin) but the value of comment_status has not changed.
Any help with this will be greatly appreciated.
{
"id": 1122,
"date": "2022-02-03T21:24:32",
"date_gmt": "2022-02-03T19:24:32",
"guid": {
"rendered": "https:\\/\\/www.example.com\\/?p=1122"
},
"modified": "2022-02-03T21:24:32",
"modified_gmt": "2022-02-03T19:24:32",
"slug": "",
"status": "draft",
"type": "post",
"link": "https:\\/\\/www.example.com\\/?p=1122",
"title": {
"rendered": "title"
},
"content": {
"rendered": "",
"protected": false
},
"excerpt": {
"rendered": "",
"protected": false
},
"author": 1,
"featured_media": 0,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"template": "",
"format": "standard",
"meta": [],
"categories": [1],
"tags": [],
"acf": {
"Description": "",
"first_page_image_id": "",
"Date": "",
"Authors": "",
"Publisher": "",
"Filename": "",
"Format": "",
"Donated_by": "",
"ocr": "",
"Series": ""
},
"_links": {
"self": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122"
}
],
"collection": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts"
}
],
"about": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/types\\/post"
}
],
"author": [{
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/users\\/1"
}
],
"replies": [{
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/comments?post=1122"
}
],
"version-history": [{
"count": 1,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122\\/revisions"
}
],
"predecessor-version": [{
"id": 1123,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/posts\\/1122\\/revisions\\/1123"
}
],
"wp:attachment": [{
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/media?parent=1122"
}
],
"wp:term": [{
"taxonomy": "category",
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/categories?post=1122"
}, {
"taxonomy": "post_tag",
"embeddable": true,
"href": "https:\\/\\/www.example.com\\/wp-json\\/wp\\/v2\\/tags?post=1122"
}
],
"curies": [{
"name": "wp",
"href": "https:\\/\\/api.w.org\\/{rel}",
"templated": true
}
]
}
}
I'm pretty new to Python so forgive me here.
I'm trying to call/print/log JSON from a GET request. I need to get the id's following this tree: items > track > artists > id.
Basically im trying to just get the ID's from each track on this JSON file/list. I keep getting errors no matter how I format them. Again im new so im not sure how to call it let also run it in a loop to get all the ID's as an array. I have done it with other JSON files in the past but this one is farther in and I get the error : TypeError: list indices must be integers or slices, not str
I figured out it works when you do it by adding the [0] like this:
artists = response["items"][0]["track"]["artists"] BUT I want to loop it and get all of the Id's for each one and that option picks just one.
here is the beginning of the json so you can see the layout.
{
"href": "https://api.spotify.com/v1/me/tracks?offset=0&limit=15&market=US",
"items": [
{
"added_at": "2021-12-15T22:26:25Z",
"track": {
"album": {
"album_type": "single",
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/6MlPT0WxdWnrYcpXT8GZF8"
},
"href": "https://api.spotify.com/v1/artists/6MlPT0WxdWnrYcpXT8GZF8",
"id": "6MlPT0WxdWnrYcpXT8GZF8",
"name": "PARKFORD",
"type": "artist",
"uri": "spotify:artist:6MlPT0WxdWnrYcpXT8GZF8"
}
],
"external_urls": {
"spotify": "https://open.spotify.com/album/4o2d8uBTyMfJeaJqSXn9tP"
},
"href": "https://api.spotify.com/v1/albums/4o2d8uBTyMfJeaJqSXn9tP",
"id": "4o2d8uBTyMfJeaJqSXn9tP",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/ab67616d0000b27332bcd9e1b2234c6cd6b2b2ec",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/ab67616d00001e0232bcd9e1b2234c6cd6b2b2ec",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/ab67616d0000485132bcd9e1b2234c6cd6b2b2ec",
"width": 64
}
],
"name": "There's Nothing in the Rain",
"release_date": "2021-11-25",
"release_date_precision": "day",
"total_tracks": 1,
"type": "album",
"uri": "spotify:album:4o2d8uBTyMfJeaJqSXn9tP"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/6MlPT0WxdWnrYcpXT8GZF8"
},
"href": "https://api.spotify.com/v1/artists/6MlPT0WxdWnrYcpXT8GZF8",
"id": "6MlPT0WxdWnrYcpXT8GZF8",
"name": "PARKFORD",
"type": "artist",
"uri": "spotify:artist:6MlPT0WxdWnrYcpXT8GZF8"
here is the code I have written out
uri = MY_LIKED_SONGS
headers = {
"Authorization": f'Bearer {tokens["access_token"]}',
"Content-Type": "application/json",
}
r = requests.get(uri, headers=headers)
response = r.json()
# return response
artist_ids = {}
data = json.dumps(response)
for artist_ids in data["items"]["track"]:
logger.info(artist_ids["items"]["track"]["artists"]["id"])
print(artist_ids["_source"]["items"][0]["track"]["id"])
tracks = response["items"]["track"][0]["artists"]["id"]
Here when you do json.dumps(), it converts a Python object into a json string. In order to iterate through json object you need to convert it into json object. For that you have to use json.loads() then you can get artist id from that.
data = json.loads(json.dumps(response))
for item in data["items"]:
for artist in item['track']['album']['artists']:
print(artist['id'])
This might be helpful.
As title says, im trying to see how if a playlist has a playlist image cover so that it doesn't try to load one that doesnt exist.
Here is my method:
currentPlaylist = spotifyObject.user_playlist(username, playlistManageURI)
if ['images'][0] in currentPlaylist:
playlistCover_url = currentPlaylist['images'][0]['url']
image = QImage()
image.loadFromData(requests.get(playlistCover_url).content)
self.playlistCover.setScaledContents(True)
self.playlistCover.setPixmap(QPixmap(image))
else:
print('Playlist Cover doesnt exist!')
which while if a playlist that does have an image cover does load, if i try to load one with an image cover that doesnt exist, it gives me
IndexError: list index out of range
here is how currentPlaylist looks like with a playlist that does have a cover
{
"collaborative": false,
"description": "",
"external_urls": {
"spotify": "https://open.spotify.com/playlist/xxxxxxxx"
},
"followers": {
"href": null,
"total": 4
},
"href": "https://api.spotify.com/v1/playlists/xxxxxxxx?additional_types=track",
"id": "xxxxxx",
"images": [
{
"height": null,
"url": "https://i.scdn.co/image/ab67706c0000bebbcab54ad44bbf6dd124838df1",
"width": null
}
],
"name": "xxxxx",
"owner": {
"display_name": "xxxxx",
"external_urls": {
"spotify": "https://open.spotify.com/user/xxxxxxxx"
},
"href": "https://api.spotify.com/v1/users/xxxx",
"id": "xxxxx",
"type": "user",
"uri": "spotify:user:xxxx"
and this is how it looks like without a cover (total blank playlist)
{
"collaborative": false,
"description": "xxxx",
"external_urls": {
"spotify": "https://open.spotify.com/playlist/xxxxxx"
},
"followers": {
"href": null,
"total": 0
},
"href": "https://api.spotify.com/v1/playlists/xxxxxx?additional_types=track",
"id": "xxxxxx",
"images": [],
"name": "xxxxxx",
"owner": {
"display_name": "xxxxx",
"external_urls": {
"spotify": "https://open.spotify.com/user/xxxxx"
},
"href": "https://api.spotify.com/v1/users/xxxx",
"id": "xxxxxxxx",
"type": "user",
"uri": "xxxxxxx"
If "images" always exists in currentPlaylist irrespective of whether currentPlaylist['images'] is empty or not.
if currentPlaylist['images']:
...
Otherwise
if "images" in currentPlaylist and currentPlaylist["images"]:
...
solved with this usage:
if currentPlaylist.get('images') == []:
print('no image found in playlist!')
else:
print(['images'][0])
playlistCover_url = currentPlaylist['images'][0]['url']
image = QImage()
image.loadFromData(requests.get(playlistCover_url).content)
self.playlistCover.setScaledContents(True)
self.playlistCover.setPixmap(QPixmap(image))
I want to fetch the value of each api3 in this json object where each array has api3 value.
{
"count": 10,
"result": [
{
"type": "year",
"year": {
"month": {
"api1": {
"href": "https://Ap1.com"
},
"api2": {
"href": "FETCH-CONTENT"
},
"api3": {
"href": "https://Ap3.com"
},
"api4": {
"href": "https://Ap4.com"
}
},
"id": "sdvnkjsnvj",
"summary": "summeryc",
"type": "REST",
"apiId": "mlksmfmksdfs",
"idProvider": {
"id": "sfsmkfmskf",
"name": "Apikey"
},
"tags": []
}
},
{
"type": "year1",
"year": {
"month": {
"api1": {
"href": "https://Ap11.com"
},
"api2": {
"href": "FETCH-CONTENT-1"
},
"api3": {
"href": "https://Ap13.com"
},
"api4": {
"href": "https://Ap14.com"
}
},
"id": "sdvnkjsnvj",
"summary": "summeryc",
"type": "REST",
"apiId": "mlksmfmksdfs",
"idProvider": {
"id": "sfsmkfmskf",
"name": "Apikey"
},
"tags": []
}
},
I am able to get the whole json object and first value inside it.
with open('C:\python\examplee.json','r+') as fr:
data = json.load(fr)
print(data["result"])
Thank you in advance for helping me figuring this.
For each element in list of result key, get the value for the nested dictionary within item
print([item['year']['month']['api3'] for item in data['result']])
The output will be [{'href': 'https://Ap3.com'}, {'href': 'https://Ap13.com'}]
Or if you want to get the href value as well
print([item['year']['month']['api3']['href'] for item in data['result']])
The output will be
['https://Ap3.com', 'https://Ap13.com']
So your whole code will look like
data = {}
with open('C:\python\examplee.json','r+') as fr:
data = json.load(fr)
print([item['year']['month']['api3']['href'] for item in dct['result']])
Looks like your JSON schema is static so you can just use this:
print([x['year']['month']['api3']['href'] for x in data['result']])
will return you:
['https://Ap3.com', 'https://Ap13.com']
I am trying to use the HubSpot CRM API to get "All Deals".
The API endpoint is: https://api.hubapi.com/deals/v1/deal/all?hapikey=demo
The JSON returned looks like this...
{
"deals": [
{
"portalId": 62515,
"dealId": 18039629,
"isDeleted": false,
"associations": {
"associatedVids": [],
"associatedCompanyIds": [],
"associatedDealIds": []
},
"properties": {
"dealname": {
"value": "Company",
"timestamp": 1457040864519,
"source": "API",
"sourceId": null
},
"amount": {
"value": "10",
"timestamp": 1457040864519,
"source": "API",
"sourceId": null
},
"closedate": {
"value": "",
"timestamp": 1457040864519,
"source": "API",
"sourceId": null
},
"hubspot_owner_id": {
"value": "11626092",
"timestamp": 1457046177648,
"source": "SALESFORCE",
"sourceId": null
},
"hs_lastmodifieddate": {
"value": "1457046177662",
"timestamp": 1457046177662,
"source": "CALCULATED",
"sourceId": null
},
"hubspot_owner_assigneddate": {
"value": "1457046177648",
"timestamp": 1457046177648,
"source": "SALESFORCE",
"sourceId": null
},
"num_associated_contacts": {
"value": "0",
"timestamp": 0,
"source": "CALCULATED",
"sourceId": null
},
"hs_createdate": {
"value": "1457040864535",
"timestamp": 1457040864535,
"source": null,
"sourceId": null
},
"createdate": {
"value": "1457040864535",
"timestamp": 1457040864535,
"source": null,
"sourceId": null
},
"hs_salesforceopportunityid": {
"value": "00628000007nRyuAAE",
"timestamp": 1457046177648,
"source": "SALESFORCE",
"sourceId": null
}
},
"imports": []
},
{
"portalId": 62515,
"dealId": 18040854,
"isDeleted": false,
"associations": {
"associatedVids": [],
"associatedCompanyIds": [],
"associatedDealIds": []
},
"properties": {
"dealname": {
"value": "5678",
"timestamp": 1457042290572,
"source": "API",
"sourceId": null
},
"amount": {
"value": "750000.0",
"timestamp": 1457042290572,
"source": "API",
"sourceId": null
},
"closedate": {
"value": "",
"timestamp": 1457042290572,
"source": "API",
"sourceId": null
},
"hs_lastmodifieddate": {
"value": "1457042290592",
"timestamp": 1457042290592,
"source": "CALCULATED",
"sourceId": null
},
"num_associated_contacts": {
"value": "0",
"timestamp": 0,
"source": "CALCULATED",
"sourceId": null
},
"hs_createdate": {
"value": "1457042290592",
"timestamp": 1457042290592,
"source": null,
"sourceId": null
},
"createdate": {
"value": "1457042290592",
"timestamp": 1457042290592,
"source": null,
"sourceId": null
}
},
"imports": []
}
],
"hasMore": true,
"offset": 1467187
}
And I understand that if hasMore==true, then you are supposed to grab the offset and include it in another API call something like this: https://api.hubapi.com/deals/v1/deal/all?hapikey=demo&offset=1467187
And then keep doing that until hasMore==false.
I am using the following code to extract the first chunk of JSON from the API:
import requests
url = "https://api.hubapi.com/deals/v1/deal/all"
querystring = {"hapikey":"demo"}
headers = {
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
So... my question is that now I am getting my JSON, how do I:
1) Read one chunk of JSON
2) If hasMore==true then go do #1 again
3) ElseIf hasMore==false then combine ALL the JSON from ALL iterations of #1 above into one big JSON
4) Return the value from #3
Any help please?
Working solution
import json
import requests
url = "https://api.hubapi.com/deals/v1/deal/all"
querystring = {"hapikey":"demo"}
headers = {
'cache-control': "no-cache"
}
all_deals = []
response = requests.request("GET", url, headers=headers, params=querystring).json()
for deal in response['deals']:
all_deals.append(deal)
hasMore = response['hasMore']
offset = response['offset']
while hasMore:
querystring = {
"hapikey":"demo",
"offset":offset
}
response = requests.request("GET", url, headers=headers, params=querystring).json()
for deal in response['deals']:
all_deals.append(deal)
hasMore = response['hasMore']
offset = response['offset']
print(json.dumps(all_deals))