简体   繁体   中英

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 )
    

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM