Search code examples
pythonjsonslack

Accessing Nested Json Keys in Slack API - Python


Having trouble parsing the JSON response in Python. I'm looking to return the object that correlates with the ID in the for loop in the below code but receiving the error:

TypeError: string indices must be integers

If I remove '[0]' in the data variable

TypeError: 'builtin_function_or_method' object is not subscriptable

Code:

import requests
import json

def get_slackusers():
    uri = "https://slack.com/api/users.list?token=tokenhere"

    try:
        response = requests.get(uri)
    except requests.exceptions.RequestException as error:
        print(error)
    

    data = json.loads(response.text)['members'][0]

    for i in data:
        if i['id'] == 'slackIDhere':
            print[i]

Any help is appreciated. Thank you.


Solution

  • Was missing correct brackets, please see below for solution.

    data = json.loads(response.text)['members']
        
    for i in data:
            if i['id'] == 'SlackIDHere':
                print([i])