1

I am trying to access the value for a field that is part of an array within JSON data. Here is the JSON Data (I :

{
"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,
        }
    ]}}}

I am only trying to pull the values for the fields "id" which appears in the "campaigns" array. Here is what the section of my code that I am using to accomplish this looks like:

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")

When using this, I get back the entire value for the "campaigns" array instead of just the ids for all of the campaigns. Can anyone help point out what I am doing wrong here? I am still fairly new to Python.

2 Answers 2

2

First off, you can use api_response.json() to get the response as a JSON dictionary.

Second, since the value keyed with campaigns is a list, you should either use a list comprehension or map to collect 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] 
Sign up to request clarification or add additional context in comments.

1 Comment

I am not sure how it worked and gave correct result with the missing ) and without using .get('campaigns',[])
1

Use the following:

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

It's a list comprehension that sets filtered_campaigns equal to a list of IDs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.