【问题标题】:Accessing value of field within array from JSON data从 JSON 数据访问数组中字段的值
【发布时间】:2025-12-31 20:25:01
【问题描述】:

我正在尝试访问作为 JSON 数据中数组的一部分的字段的值。这是 JSON 数据(我:

{
"response":
{
"test-item": {
    "id": 125252,
    "code": null,
    "name": "test_1",
    "section_id": 85552653,
    "state": "active",
    "start_date": "2016-10-10 00:00:00",
    "end_date": null,
    "timezone": "US/Pacific",
    "discrepancy_pct": 0,
    "publishers_allowed": "all",
    "campaigns": [
        {
            "id": 85669995691,
            "name": "test_campaign",
            "profile_id": 43562,
            "inventory_type": "direct",
            "state": "active",
            "priority": 5,
        },
        {
            "id": 800099981123,
            "name": "test_campaign_2",
            "profile_id": 12562,
            "inventory_type": "direct",
            "state": "active",
            "priority": 5,
        }
    ]}}}

我只是想提取出现在“campaigns”数组中的字段“id”的值。这是我用来完成此操作的代码部分的样子:

url = "https://api.example.com"  

header = {"Authorization": authorization_code}

api_response = requests.get(url, headers=header)

test_response = json.loads(api_response.text)

filtered_campaigns = test_response.get("response", {}).get("test-item", 
{}).get("campaigns", "id")

使用它时,我会取回“campaigns”数组的整个值,而不仅仅是所有广告系列的 id。谁能帮忙指出我在这里做错了什么?我对 Python 还是很陌生。

【问题讨论】:

    标签: python arrays json python-2.7


    【解决方案1】:

    首先,您可以使用api_response.json() 将响应作为 JSON 字典获取。

    其次,由于campaigns键控的值是一个列表,你应该使用列表推导或map来收集ids:

    >>> from operator import itemgetter
    >>> test_response = api_response.json()
    >>> filtered_campaigns = map(
            itemgetter("id"), 
            test_response.get("response", {}).get("test-item", {}).get("campaigns", []))
    
    [85669995691, 800099981123] 
    

    【讨论】:

    • 我不确定它是如何工作的,并且在缺少 ) 和不使用 .get('campaigns',[]) 的情况下给出了正确的结果
    【解决方案2】:

    使用以下内容:

    filtered_campaigns = [x['id'] for x in test_response['response']['test-item']['campaigns']]
    

    它是一个列表推导式,将filtered_campaigns 设置为一个ID 列表。

    【讨论】: