How can I safely grab a nested value in this response JSON while filling a blank when no value is found?

Question:

I have been trying for a few hours to figure out what is wrong with this code. I have received errors telling me a dict is a string (I print the type of a variable and it tells me it’s dict. Then immediately after I can’t use .get() because it’s a string??)

Anyways, here is my code.

  APResponse = requests.post(APurl, headers=headers, json={'offset': str(AssetPandaCurrentUser), 'limit': '1'})
    APResponseJSON = json.loads(APResponse.text)

    AssetPandaUserDict = {
        "Username": [APResponseJSON.get('objects', {}).get('data', 'field_52')],
        "Role": [APResponseJSON.get(['objects'][0].get(['data'].get(['field_49'].get(['value']))))],
        "User Status": [APResponseJSON['objects'][0]['data']['field_6']['value']],
        "Laptop Status": [],
        "Laptop Serial": []
    }

This is the JSON that is outputted by the API, just so you don’t have to call it yourself:

{"totals":{"objects":2637,"group_totals":0,"offset":0,"limit":1},"entity_actions":{},"listing_fields":["field_1","field_5","field_6"],"not_viewable":2637,"objects":[{"id":"5f4da7ad3b1816173cabc50a","display_name":"bob.joe","action_objects":[{"_id":{"$oid":"5ff8e37787e62c6085cfdaf2"},"account_id":19284,"array_values":["2021-01-08 22:57:59","Billy Mike / 01/08/2021 05:57 PM"],"change_source":"Web","change_trigger":"Offboard Employee","created_at":"2021-01-08T22:57:59.126Z","date_format":null,"embedded_into_object_id":null,"entity_action_id":222965,"entity_id":126590,"google_calendar_sync":null,"gps_coordinates":null,"linked_action_object_id":null,"low_values":{"field_1":"2021-01-08 22:57:59","grouped_action_id":"Billy Mike / 01/08/2021 05:57 pm"},"modifier_id":null,"next_step_reservation_uid":"","old_id":null,"parent_action_object_id":null,"predefined_forms":null,"reservation_notification":[],"reservation_uid":"","reserve_for":{},"returned":false,"state":"","status":"","updated_at":"2021-01-08T22:57:59.126Z","user_id":"1224858","value_ids":{"grouped_action_id":1655215},"values":{"field_1":"2021-01-08 22:57:59","grouped_action_id":"Billy Mike / 01/08/2021 05:57 PM"},"version":1,"id":"5ff8e37787e62c6085cfdaf2"}],"secondary_name":"Bob Joe","display_with_secondary":"bob.joe u003cBob Joeu003e","field_values":["Bob Joe","Inactive"],"data":{"field_52":"bob.joe","field_1":"Bob Joe","field_2":"[email protected]","field_3":"555-555-1234","field_49":{"id":"5f4d3c053b18161762b412ca","value":"Member Support"},"field_6":{"id":"239241","value":"Inactive"},"field_54":"2020-04-13","field_56":"no"},"object_depreciation":false,"object_appreciation":false,"share_url":"https://login.assetpanda.com/employees/userid","created_at":"2020-08-31T21:45:17.642Z","updated_at":"2021-01-08T17:57:59.126Z","is_editable":true,"is_deletable":true,"object_version_ids":"5","has_audit_history":false,"is_locked":false,"is_archived":false,"entity":{"id":126590,"key":"employees"}}]}

(yes it’s not pretty sadly)

I want the following to essentially be set:

AssetPandaUserDict = {
        "Username": field_52,
        "Role": value in field_52,
        "User Status": value in field_6,
        "Laptop Status": [],
        "Laptop Serial": []
    }

I have tried using .get but it tells me you cant .get() from a string no matter what I convert the response to. I have treid just doing " APResponseJSON[‘objects]’ but that throws an exception when there’s no value. Does anyone have any clue here?

Asked By: GooseAtCompany

||

Answers:

Try:

AssetPandaUserDict = {
    "Username": APResponseJSON["objects"][0]["data"]["field_52"],
    "Role": APResponseJSON["objects"][0]["data"]["field_49"]["value"],
    "User Status": APResponseJSON["objects"][0]["data"]["field_6"]["value"],
    "Laptop Status": [],
    "Laptop Serial": [],
}

print(AssetPandaUserDict)

Prints:

{
    "Username": "bob.joe",
    "Role": "Member Support",
    "User Status": "Inactive",
    "Laptop Status": [],
    "Laptop Serial": [],
}

EDIT: When field_49 is not present:

AssetPandaUserDict = {
    "Username": APResponseJSON["objects"][0]["data"]["field_52"],
    "Role": APResponseJSON["objects"][0]["data"]
    .get("field_49", {})
    .get("value", "N/A"),
    "User Status": APResponseJSON["objects"][0]["data"]["field_6"]["value"],
    "Laptop Status": [],
    "Laptop Serial": [],
}

Prints:

{
    "Username": "bob.joe",
    "Role": "N/A",
    "User Status": "Inactive",
    "Laptop Status": [],
    "Laptop Serial": [],
}
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.