Uploading a file to Slack has no response in chat - python

I'm trying to send some txt data with this code
my_file = {'file' : ('/home/suomi/_data.txt', open('/home/suomi/_data.txt', 'r'), 'txt')}
payload={
"filename":"aaaa.txt",
"token":API_BOT,
"channel":'*my_user_id*',
}
x = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)
print(x)
print(x.json())
getting this response
<Response [200]>
{'ok': True, 'file': {'id': '*private_id*', 'created': 1603941396, 'timestamp': 1603941396, 'name': 'aaaa.txt', 'title': 'aaaa', 'mimetype': 'text/plain', 'filetype': 'text', 'pretty_type': 'pretty text', 'user': '*my private user_id*', 'editable': True, 'size': 18145, 'mode': 'snippet', 'is_external': False, 'external_type': '', 'is_public': False, 'public_url_shared': False, 'display_as_bot': False, 'username': '', 'url_private': '*private url_link*', 'url_private_download': '*private url_link*', 'permalink': '*private url_link*', 'permalink_public': '*private url_link*', 'edit_link': '*private url_link*', 'preview': "*somedata*", 'preview_highlight': '<div class="CodeMirror cm-s-default CodeMirrorServer" oncopy="if(event.clipboardData){event.clipboardData.setData(\'text/plain\',window.getSelection().toString().replace(/\\u200b/g,\'\'));event.preventDefault();event.stopPropagation();}">\n<div class="CodeMirror-code">\n<div><pre>*somedata*</pre></div>\n<div><pre></pre></div>\n<div><pre>*************************************</pre></div>\n<div><pre></pre></div>\n</div>\n</div>\n', 'lines': 131, 'lines_more': 126, 'preview_is_truncated': True, 'comments_count': 0, 'is_starred': False, 'shares': {}, 'channels': [], 'groups': [], 'ims': [], 'has_rich_preview': False}}
values inside ** are replaced due to privacy.
But I'm not getting a response from my app - I have enabled right permissions and I can send normal text messages.
files:write, channels:history, channels:read, chat:write, groups:history
BTW. I'm trying to send a file to user, not channel

Related

How load nested Response JSON into a dataframe without saving in a file?

I'm attempting to load a pandas a dataframe with a heavily nesting JSON. This JSON is the result of an API code in Python. Here is the structure of the JSON file:
{
'results': [{
'accountId': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
'id': '6ed909bd16',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'NewSeptemberFile20220908',
'description': None,
'created': '2022-09-12T22:04:55.799+00:00',
'lastModified': '2022-09-12T22:06:10.838+00:00',
'lastIndexed': '2022-09-12T22:05:04.551+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '6ed909bd16',
'thumbnailId': '5f04af4d-e382-4387-9573-6d9e4bad3b68',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXX',
'id': '34344818e8',
'partition': None,
'externalId': None,
'metadata': None,
'name': '3September',
'description': None,
'created': '2022-09-09T17:55:59.696+00:00',
'lastModified': '2022-09-09T17:57:51.057+00:00',
'lastIndexed': '2022-09-09T17:56:04.544+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '34344818e8',
'thumbnailId': 'baae7ed1-a791-4481-853c-1707b40b5e77',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'id': '82da4b60ef',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'film10',
'description': None,
'created': '2022-08-22T14:24:08.442+00:00',
'lastModified': '2022-09-08T23:13:16.416+00:00',
'lastIndexed': '2022-08-22T14:24:12.605+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '82da4b60ef',
'thumbnailId': '5a5f6a71-0302-46a6-93c8-beb918c00b14',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXX',
'id': '7ea0c5e34a',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'davide_quatela--people_in_frankfurt',
'description': None,
'created': '2022-09-07T21:31:52.818+00:00',
'lastModified': '2022-09-08T22:52:52.833+00:00',
'lastIndexed': '2022-09-07T21:31:57.328+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 131,
'thumbnailVideoId': '7ea0c5e34a',
'thumbnailId': '3aba8f42-a3a7-4d77-92b0-8cabcc275a3b',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-US',
'sourceLanguages': ['en-US'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXXX',
'id': '7c45ae7ffe',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'Untitled project',
'description': None,
'created': '2022-08-17T17:36:23.72+00:00',
'lastModified': '2022-08-17T17:36:49.95+00:00',
'lastIndexed': '2022-08-17T17:36:49.95+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': False,
'hasSourceVideoFile': False,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '',
'durationInSeconds': 0,
'thumbnailVideoId': None,
'thumbnailId': '00000000-0000-0000-0000-000000000000',
'searchMatches': [],
'indexingPreset': None,
'streamingPreset': 'Default',
'sourceLanguage': 'en-US',
'sourceLanguages': ['en-US'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}
],
'nextPage': {
'pageSize': 25,
'skip': 0,
'done': True
}
}
And this is my code in Python 3.x:
url = "https://api.videoindexer.ai/" + Location + "/Accounts/" + AzVIAccountID + "/Videos?pageSize=25&skip=0&accessToken=" + iAccessToken
response = requests.get(url,headers=hdr )
### Response: 200 OK
print("If Response=200 Script run is OK : " , response.status_code)
I want the result to be like this:
Question: Is there a possibility to fetch 'name', 'id', and 'create' of all videos which are showing in the JSON result (Response API) into a dataframe directly?
If data contains the data from the question you can do:
df = pd.DataFrame(data["results"])
columns_i_want = ["id", "name", "created"]
df = df[columns_i_want]
print(df)
Prints:
id name created
0 6ed909bd16 NewSeptemberFile20220908 2022-09-12T22:04:55.799+00:00
1 34344818e8 3September 2022-09-09T17:55:59.696+00:00
2 82da4b60ef film10 2022-08-22T14:24:08.442+00:00
3 7ea0c5e34a davide_quatela--people_in_frankfurt 2022-09-07T21:31:52.818+00:00
4 7c45ae7ffe Untitled project 2022-08-17T17:36:23.72+00:00
EDIT:
url = (
"https://api.videoindexer.ai/"
+ Location
+ "/Accounts/"
+ AzVIAccountID
+ "/Videos?pageSize=25&skip=0&accessToken="
+ iAccessToken
)
response = requests.get(url, headers=hdr)
data = response.json()
# make sure the correct response is sent:
print(data)
# if above command prints correct data, you can do next:
df = pd.DataFrame(data["results"])
columns_i_want = ["id", "name", "created"]
df = df[columns_i_want]
print(df)

How to search for the video id by name in nested JSON Response?

This is my JSON response API, I want to search for the video id by name. I mean Get VideoID using Video Name.
For example: I want to input 'film10' and Python returns '82da4b60ef' as a result. I am using API Response JSON; this is the JSON:
{
'results': [{
'accountId': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
'id': '6ed909bd16',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'NewSeptemberFile20220908',
'description': None,
'created': '2022-09-12T22:04:55.799+00:00',
'lastModified': '2022-09-12T22:06:10.838+00:00',
'lastIndexed': '2022-09-12T22:05:04.551+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '6ed909bd16',
'thumbnailId': '5f04af4d-e382-4387-9573-6d9e4bad3b68',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXX',
'id': '34344818e8',
'partition': None,
'externalId': None,
'metadata': None,
'name': '3September',
'description': None,
'created': '2022-09-09T17:55:59.696+00:00',
'lastModified': '2022-09-09T17:57:51.057+00:00',
'lastIndexed': '2022-09-09T17:56:04.544+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '34344818e8',
'thumbnailId': 'baae7ed1-a791-4481-853c-1707b40b5e77',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'id': '82da4b60ef',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'film10',
'description': None,
'created': '2022-08-22T14:24:08.442+00:00',
'lastModified': '2022-09-08T23:13:16.416+00:00',
'lastIndexed': '2022-08-22T14:24:12.605+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 58,
'thumbnailVideoId': '82da4b60ef',
'thumbnailId': '5a5f6a71-0302-46a6-93c8-beb918c00b14',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-GB',
'sourceLanguages': ['en-GB'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXX',
'id': '7ea0c5e34a',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'davide_quatela--people_in_frankfurt',
'description': None,
'created': '2022-09-07T21:31:52.818+00:00',
'lastModified': '2022-09-08T22:52:52.833+00:00',
'lastIndexed': '2022-09-07T21:31:57.328+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': True,
'hasSourceVideoFile': True,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '100%',
'durationInSeconds': 131,
'thumbnailVideoId': '7ea0c5e34a',
'thumbnailId': '3aba8f42-a3a7-4d77-92b0-8cabcc275a3b',
'searchMatches': [],
'indexingPreset': 'Default',
'streamingPreset': 'Default',
'sourceLanguage': 'en-US',
'sourceLanguages': ['en-US'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}, {
'accountId': 'XXXXXXXXXXXXXXXXXX',
'id': '7c45ae7ffe',
'partition': None,
'externalId': None,
'metadata': None,
'name': 'Untitled project',
'description': None,
'created': '2022-08-17T17:36:23.72+00:00',
'lastModified': '2022-08-17T17:36:49.95+00:00',
'lastIndexed': '2022-08-17T17:36:49.95+00:00',
'privacyMode': 'Private',
'userName': 'M M',
'isOwned': True,
'isBase': False,
'hasSourceVideoFile': False,
'state': 'Processed',
'moderationState': 'OK',
'reviewState': 'None',
'processingProgress': '',
'durationInSeconds': 0,
'thumbnailVideoId': None,
'thumbnailId': '00000000-0000-0000-0000-000000000000',
'searchMatches': [],
'indexingPreset': None,
'streamingPreset': 'Default',
'sourceLanguage': 'en-US',
'sourceLanguages': ['en-US'],
'personModelId': '00000000-0000-0000-0000-000000000000'
}
],
'nextPage': {
'pageSize': 25,
'skip': 0,
'done': True
}
}
This is my code, I get the API data by the requests get method and it returns '200' that it does mean the code is working properly.
url = "https://api.video.ai/trial/Accounts//Videos/7ea0c5e34a/Index?language=af-ZA&reTranslate=false&includeStreamingUrls=true&includeSummarizedInsights=true&accessToken="
response = requests.get(url,headers=hdr )
### Response: 200 OK
print("If Response=200 Script run is OK : " , response.status_code)
So the url does not open on my end. cannot fetch the json.
using the json provided by you -
for item in json_data['results']:
if item['name'] == 'film10':
print(item['id'])
gives
82da4b60ef
You could try the following:
for result in response['results']:
if result['name'] == ('YOUR FILM NAME INPUT'):
return result['id']
As you can see the response has a list with the results called "results", so this code runs through it and check if the name equals the name you want to check.

How to iterate through a slack api response and save as local variable?

I'm trying to make a slack app and am struggling to save part of an api response as a local variable.
This is my code:
import os
import re
import time
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
load_dotenv()
#loading env variables
SLACK_APP_TOKEN = os.environ["SLACK_APP_TOKEN"]
SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
app = App(token=SLACK_BOT_TOKEN, name="SlackApp")
#app.message(re.compile("^."))#event listener listens to messages matching a wildcard regular expression
def reply(message, say):
print("Message :"+message["text"])
print("Recieved #:"+time.ctime())
#job title check
userid = message["user"]
userinfodict = app.client.users_info(
user=userid
)
print(userinfodict)
This returns an output of:
{'ok': True, 'user': {'id': 'U03PMCY1BUG', 'team_id': 'T03NH2KCQA3', 'name': 'John Doe', 'deleted': False, 'color': '9f69e7', 'real_name': 'John Doe', 'tz': 'America/New_York', 'tz_label': 'Eastern Daylight Time', 'tz_offset': -14400, 'profile': {'title': 'Business Analyst', 'phone': '', 'skype': '', 'real_name': 'John Doe', 'real_name_normalized': 'realfakename', 'display_name': '', 'display_name_normalized': '', 'fields': None, 'status_text': '', 'status_emoji': '', 'status_emoji_display_info': [], 'status_expiration': 0, 'avatar_hash': 'gb8c5320087d', 'first_name': 'John', 'last_name': '', 'image_24': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=24&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-24.png', 'image_32': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=32&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-32.png', 'image_48': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=48&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-48.png', 'image_72': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=72&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-72.png', 'image_192': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=192&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-192.png', 'image_512': 'https://secure.gravatar.com/avatar/b8c5320087d1218227d9c8f54866a381.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0014-512.png', 'status_text_canonical': '', 'team': 'T03NH2KCQA3'}, 'is_admin': True, 'is_owner': True, 'is_primary_owner': True, 'is_restricted': False, 'is_ultra_restricted': False, 'is_bot': False, 'is_app_user': False, 'updated': 1659555324, 'is_email_confirmed': True, 'who_can_share_contact_card': 'EVERYONE'}}
How do I save a part of this output as a local variable?
In particular the job title:
...'profile': {'title': 'Business Analyst',...
It is not a dictionary,
it is of type: <class 'slack_sdk.web.slack_response.SlackResponse'>
Since you already have that output dict, extract the title with [] operator, aka __getitem__():
userinfodict['user']['profile']['title'] # => 'Business Analyst'

How to subtract key out of Json api response and check if there are more keys, and if so put them in a list?

So I have a complex problem, I have a JSON API response with the key: 'key' in 'persons'
but in some cases there is more than 1 'key', I tried to make a for loop to go through the response but it will print it like 20 times. Also, I have no idea to put those 'keys' in a list or a place where I can access them.
to make it a bit easier i have the response that i get out of my .request
{'id': 'a2b1109e-e142-4559-984c-3f9997b1db6a', 'externalId': None, 'name': 'tyr', 'description': '', 'client': '', 'reference': '56345', 'isMonitoring': False, 'monitoringSince': None, 'hasRiskProfile': True, 'riskProfile': 5, 'monitorFrequency': 4, 'mainBindable': None, 'organizationId': '65647b97-5ada-4362-bb3f-cae016722be6', 'userId': 'dd3cc015-e5cf-4a03-9408-74b102900836', 'createDate': '2021-03-23T11:29:55.2027037Z', 'updateDate': '2021-03-23T11:29:55.2027039Z', 'lastMonitorDate': '2021-03-23T11:29:55.2027039Z', 'persons': [{'firstname': 'ya', 'surname': 'o', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'ya o', 'externalId': None, 'key': '8b92c210-eee6-4ab2-a093-48e4428af7f8', 'searchResults': [], 'requests': [], 'createDate': '2021-03-23T11:29:57.3853552Z', 'updateDate': '2021-03-23T11:29:57.3853553Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': False, 'notes': []}], 'businesses': [], 'monitorIds': [], 'addresses': [], 'notifcations': [], 'monitors': []}
the number of keys can be different each time, so I will need to make a check to see if the key that gets back is already existing if so then do nothing, if the key is not existing then save that key in a variable.
here is a example of a response when there are 2 keys"key",
{'id': '44b2203b-b2c8-41f0-8fde-b697ec02a8c8', 'externalId': None, 'name': 'tyr', 'description': '', 'client': '', 'reference': '56345', 'isMonitoring': False, 'monitoringSince': None, 'hasRiskProfile': True, 'riskProfile': 5, 'monitorFrequency': 4, 'mainBindable': None, 'organizationId': '65647b97-5ada-4362-bb3f-cae016722be6', 'userId': 'dd3cc015-e5cf-4a03-9408-74b102900836', 'createDate': '2021-03-23T20:58:53.0345703Z', 'updateDate': '2021-03-23T20:58:53.0345705Z', 'lastMonitorDate': '2021-03-23T20:58:53.0345706Z', 'persons': [{'firstname': 'marnox', 'surname': 'bolier', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'marnox bolier', 'externalId': None, 'key': '68e4a9ad-2431-490f-a216-61a0cbd81c57', 'searchResults': [{'at': '2021-03-23T20:58:54.6796804Z', 'totalHits': 0, 'type': None, 'results': [{'paymentRequired': False, 'service': None, 'source': 'CIR', 'items': [], 'count': 0}, {'paymentRequired': False, 'service': 'VaV61', 'source': 'Entity', 'items': [], 'count': 0}], 'requestable': {'id': 'bf9dea30-2f4a-467a-a7b1-6765ceaee517', 'name': 'marnox bolier', 'createDate': '2021-03-23T20:58:55.5409494Z', 'updateDate': '2021-03-23T20:58:55.5409495Z', 'type': 'NotFoundPerson', 'sourceKey': 'A135D3C449EA15C66B6444611E2C97EC', 'picture': None, 'properties': {}, 'resultKey': None, 'data': None, 'archivedDate': None, 'isArchived': False}, 'cachedResult': False}], 'requests': [{'id': '57866866-85c4-43d8-8caa-b47a90b12be4', 'name': 'marnox bolier (TO UPDATE)', 'createDate': '2021-03-23T20:58:56.3090064Z', 'updateDate': '2021-03-23T20:58:56.3090064Z', 'type': 'NotFoundPerson', 'sourceKey': 'AB1AD3379D84D5D2404CF8326CDA054D', 'picture': None, 'properties': {}, 'resultKey': None, 'data': None, 'archivedDate': None, 'isArchived': False}], 'createDate': '2021-03-23T20:58:53.912784Z', 'updateDate': '2021-03-23T20:58:53.912784Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': True, 'notes': []}, {'firstname': 'marnix', 'surname': 'bolier', 'dateOfBirth': '', 'updatedWithIdinIdentificationRequestPerson': None, 'relatedList': None, 'updatedWithIdinIdentificationRequestPersonDate': None, 'history': [], 'fullname': 'marnix bolier', 'externalId': None, 'key': 'c0475154-530e-4802-b215-1d26a2c7f208', 'searchResults': [], 'requests': [], 'createDate': '2021-03-23T20:58:56.9078002Z', 'updateDate': '2021-03-23T20:58:56.9078002Z', 'archivedDate': None, 'isArchived': False, 'hasPepSearchResults': False, 'notes': []}], 'businesses': [], 'monitorIds': [], 'addresses': [], 'notifcations': [], 'monitors': []}
update i solved my first problem getting more than 1 key with a for loop:
for persons in api_response['persons']:
print(persons['key'])
output:
0b8eb227-0105-40a3-bc8b-8e3ef345a3f3
d9b68e7a-ffdd-44ea-86a4-ea4c541146b4
how can I only save the last result so in this case
d9b68e7a-ffdd-44ea-86a4-ea4c541146b4
Assuming you are using requests to fetch the data from the api your response will simply have a json() function attached. Meaning you can do something like this:
import requests
response = requests.get("example.com/api/random/endpoint")
data = response.json()
The json function in turn does the equivalent of json.loads() with the content of the response. Assuming your API returns a JSON object this will be converted to a dictionary (in accordance with the json conversion table.
After that you can follow go2nirvana's answer and manipulate this dictionary as you would any dict. For example using data.pop("key") to remove the value at that key, iterate over the dictionary, or whatever else you can do with a dictionary.
Admittedly your question is a bit vague and I am not sure exactly what you want to do with the data you recieve, but this is how you get that data in a form that is easy to work with within python.

Convert JSON string to a list in order to enumerate

End goal: I want to get 'userid', 'username', and 'email' from a JSON string that I pulled from Slack. When I try converting it to a list, it only gives me the first three keys, it won't pull the nested data.
Here's my code:
from slackclient._client import SlackClient
import json
def main():
token = "XXXXX"
sc = SlackClient(token)
users = get_users(sc)
print(users)
print(list(users))
def get_users(sc):
print("Get Users")
print(80 * "=")
#call the users.list api call and get list of users
users = (sc.api_call("users.list"))
users = json.dumps(users)
users = json.loads(str(users))
return users
main()
My problem is "print(users)" prints me out an entire JSON string and "print(list(users))" only prints the first un-nested keys. Here's an example of what my output is.
"print(list(users))" gives me the following:
['members', 'cache_ts', 'ok']
"print(users)" gives me the following, but I can't pull anything specific from it as a string.
{'members': [{'real_name': 'XXXXXX', 'is_ultra_restricted': False, 'name': 'XXXXX', 'is_primary_owner': False, 'id': 'XXXXXX', 'color': '4bbe2e', 'status': None, 'profile': {'image_32': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=32&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0006-32.png', 'real_name': 'XXXXXX', 'first_name': 'XXXXXX', 'avatar_hash': 'g140a3a97c34', 'email': 'XXXXXXX#XXXXX.COM', 'image_192': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=192&d=https%3A%2F%2Fa.slack-edge.com%2F7fa9%2Fimg%2Favatars%2Fava_0006-192.png', 'image_24': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=24&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0006-24.png', 'real_name_normalized': 'XXXXXX', 'image_512': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F7fa9%2Fimg%2Favatars%2Fava_0006-512.png', 'last_name': 'XXXXXX', 'image_48': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=48&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0006-48.png', 'image_72': 'https://secure.gravatar.com/avatar/140a3a97c34e956bb6692fb0f1bd325e.jpg?s=72&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0006-72.png'}, 'deleted': False, 'tz': 'America/Los_Angeles', 'tz_offset': -28800, 'is_restricted': False, 'is_admin': False, 'team_id': 'T3854BB3K', 'has_2fa': False, 'is_bot': False, 'tz_label': 'Pacific Standard Time', 'is_owner': False}, {'real_name': 'XXXXXXX, 'is_ultra_restricted': False, 'name': 'XXXXXXX', 'is_primary_owner': True, 'id': 'XXXXXXX', 'color': '9f69e7', 'status': None, 'profile': {'image_32': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=32&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0001-32.png', 'real_name': 'XXXXXX', 'first_name': 'XXXXX', 'avatar_hash': 'g98e886a882b', 'email': 'XXXXXXX#gmail.com', 'image_192': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=192&d=https%3A%2F%2Fa.slack-edge.com%2F7fa9%2Fimg%2Favatars%2Fava_0001-192.png', 'image_24': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=24&d=https%3A%2F%2Fa.slack-edge.com%2F66f9%2Fimg%2Favatars%2Fava_0001-24.png', 'real_name_normalized': 'XXXXXXX', 'image_512': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F7fa9%2Fimg%2Favatars%2Fava_0001-512.png', 'last_name': 'XXXXXX', 'image_48': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=48&d=https%3A%2F%2Fa.slack-edge.com%2F0180%2Fimg%2Favatars%2Fava_0001-48.png', 'image_72': 'https://secure.gravatar.com/avatar/98e886a882b9eb8476b39519a0007b50.jpg?s=72&d=https%3A%2F%2Fa.slack-edge.com%2F3654%2Fimg%2Favatars%2Fava_0001-72.png'}, 'deleted': False, 'tz': 'America/Chicago', 'tz_offset': -21600, 'is_restricted': False, 'is_admin': True, 'team_id': 'T3854BB3K', 'has_2fa': False, 'is_bot': False, 'tz_label': 'Central Standard Time', 'is_owner': True}, {'real_name': 'Talla', 'is_ultra_restricted': False, 'name': 'talla', 'is_primary_owner': False, 'id': 'XXXXXX', 'color': 'e7392d', 'status': None, 'profile': {'api_app_id': 'A0P3RDP0R', 'image_32': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_32.png', 'image_original': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_original.png', 'real_name': 'Talla', 'always_active': False, 'first_name': 'Talla', 'bot_id': 'B38SQ12EN', 'avatar_hash': '0864de31dc83', 'image_1024': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_512.png', 'image_192': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_192.png', 'image_24': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_24.png', 'real_name_normalized': 'Talla', 'image_512': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_512.png', 'image_48': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_48.png', 'image_72': 'https://avatars.slack-edge.com/2016-11-30/111583483766_0864de31dc83b2d4ad5b_72.png'}, 'deleted': False, 'tz': None, 'tz_offset': -28800, 'is_restricted': False, 'is_admin': False, 'team_id': 'T3854BB3K', 'is_bot': True, 'tz_label': 'Pacific Standard Time', 'is_owner': False}, {'real_name': 'slackbot', 'is_ultra_restricted': False, 'name': 'slackbot', 'is_primary_owner': False, 'id': 'USLACKBOT', 'color': '757575', 'status': None, 'profile': {'image_32': 'https://a.slack-edge.com/2fac/plugins/slackbot/assets/service_32.png', 'real_name': 'slackbot', 'first_name': 'slackbot', 'fields': None, 'last_name': '', 'image_192': 'https://a.slack-edge.com/66f9/img/slackbot_192.png', 'image_24': 'https://a.slack-edge.com/0180/img/slackbot_24.png', 'real_name_normalized': 'slackbot', 'image_512': 'https://a.slack-edge.com/1801/img/slackbot_512.png', 'avatar_hash': 'sv1444671949', 'image_48': 'https://a.slack-edge.com/2fac/plugins/slackbot/assets/service_48.png', 'image_72': 'https://a.slack-edge.com/0180/img/slackbot_72.png'}, 'deleted': False, 'tz': None, 'tz_offset': -28800, 'is_restricted': False, 'is_admin': False, 'team_id': 'T3854BB3K', 'is_bot': False, 'tz_label': 'Pacific Standard Time', 'is_owner': False}], 'ok': True, 'cache_ts': 1480600947}
json.loads() returns a dictionary, and by default iterating a dictionary is actually iterating over the keys.
try iterating over users.items() to get (key,value) pairs.

Categories