Saving a nested json value to a variable in python

Question:

I am trying to save a json value retrieved by an API GET to a variable so that I can POST it later into an API call. Here is what I have so far

import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import objectpath

auth = HTTPBasicAuth("Username", "PAssword")
departmentname = "IT" #sys.argv[1]
url = "http://url.com".format( departmentname ) 
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

response = requests.request(
    "GET",
    url,
    headers=headers,
    auth=auth,
)
r = json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))
#print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
response.json()

I then get the response:

{
    "departments": [
        {
            "created_at": "2022-06-01T17:15:32Z",
            "custom_fields": {},
            "description": "IT Service Team",
            "domains": [],
            "head_user_id": #####,
            "id": ######,
            "name": "IT",
            "prime_user_id": null,
            "updated_at": "2022-06-07T16:35:25Z"
        }
    ]
}

I tried print(response['departments'][0][id'][0]) but I get an error that says string indices must be be integers.
I also tried using a for loop but get the same error.

Asked By: TL_Arwen

||

Answers:

try

r = json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))

print(r['departments'][0]['id'][0]) 

Answered By: khaled koubaa

Got it working by adding an additional json.loads:

    d = json.loads(r)
    id = d['departments'][0]['id']
Answered By: TL_Arwen
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.