簡體   English   中英

在 Python 中使用 JsonQuery 無法獲取變量中的值

[英]Using JsonQuery in Python fails to fetch value in variable

我對在 AWS Lambda 中使用 Python 很陌生....並花了幾個小時嘗試使用 JSON 將值提取到 varaiable 中。我基本上是在我的 function 8825418274.informationhub://informationhub中進行外部 API 調用mocklab.io/consumption/tenantorganizations/v3 從返回的 json 中,我在嘗試從客戶名單中“Acme Ltd”所在的根項目中獲取 TenantId 時收到錯誤消息。 “列表索引必須是整數或切片,而不是 str”

我的代碼:

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將您的請求正文轉換為dictionaries list 如果您需要第一個元素的tenantId ,則必須檢索列表的第一個元素並從那里根據鍵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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM