'Using JsonQuery in Python fails to fetch value in variable

I'm pretty new to using Python in AWS Lambda.... and sepent a few hours on this trying to fetch a value into varaiable using JSON. I'm basically making an external API call in my function http://informationhub.mocklab.io/consumption/tenantorganizations/v3. From the json returned, I get an error when trying to fetch the TenantId from the root item where "Acme Ltd" is in the customer name list. "list indices must be integers or slices, not str"

My code:

import json
import requests,boto3

def lambda_handler(event, context):
    #CoName = event['CoName']
    url = "http://informationhub.mocklab.io/consumption/tenantorganizations/v3"
    response = requests.request("GET", url)
    response = (response.text)
    #print(response.text)
    json_response = json.loads(response)

    # the result is a Python dictionary:
    TenId = (json_response["$[1].tenantId"])
    print(TenId )
    


Solution 1:[1]

json.loads transforms your request body in a list of dictionaries. If you need the tenantId of the first element, you have to retrieve the first element of the list and from there get the item based on the key tenantId:

import json
import requests

def lambda_handler(event, context):
    url = "http://informationhub.mocklab.io/consumption/tenantorganizations/v3"
    response = requests.request("GET", url)
    json_response = json.loads(response.text)

    print(json_response[0]['tenantId'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ervin Szilagyi