Problem retrieving values from multi nested JSON in Python

I am having a lot of trouble attempting to get all values from a multi level nested JSON in Python. I am new to Python and have the basics but no matter what I try here I am getting errors.

Here is my code, I am pulling in a response and converting it to JSON from an API call. I then need to store the data in my SQL Server from the JSON response. Everything except the values on lower levels of the JSON is working flawlessly.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import requests
import random
import json
import string
import time
import pyodbc
import textwrap
#proxies:
proxies = {
'http': 'http://proxy.me.com:3128',
'https': 'http://proxy.me.com:3128'}
payload_login = json.dumps({
"un": "Admin",
"passwd": "2020admin"
})
headers_login = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
#login_request:
url = "http://api.testing/login"
session = requests.Session()
session.verify = False
response = requests.request("POST", url, headers=headers_login, data=payload_login,proxies=proxies)
assert response.status_code == 200
json_data = response.json()
json_str = json.dumps(json_data, indent=4)
auth_token = json_data["access_token"]
print("Bearer "+auth_token)
auth_token2 = "Bearer " + auth_token
response.close()
time.sleep(1)
#return auth_token
with open(r'C:\Credentials\credentials.json', 'r') as json_file:
credentials = json.load(json_file)
credentials1 = credentials['CloudP']
conn_str1 = (
f"DRIVER=SQL Server;"
f"SERVER={credentials1['host']};"
f"DATABASE={credentials1['database_name']};"
f"UID={credentials1['username']};"
f"PWD={credentials1['password']};"
"ENCRYPT=no"
)
conn1 = pyodbc.connect(conn_str1, timeout=100)
cursor1 = conn1.cursor()
next_headers_get = {
'Accept': 'application/json',
'Authorization': auth_token2
}
url2 = "http://api.testing/proddetail"
response3 = requests.request("GET", url2, headers=next_headers_get,proxies=proxies)
#assert response2.status_code == 200
json_data3 = response3.json()
json_str3 = json.dumps(json_data3, indent=4)
insert_query3 = """
INSERT INTO dbo.proddetail.resources (ItemID, ResourceID, ResourceType, RST_DisplayName, MapID, MapName)
VALUES (?, ?, ?, ?, ?, ?)
"""
for content in json_data3['content']:
id = content['id']
resource_id = content['resourceId']
resource_type = content['resourceType']
resource_type_display_name = content['resourceTypeDisplayName']
map_id = content['location']['properties']['mapId']
map_name = content['location']['properties']['mapName']
cursor3.execute(insert_query3, ([id, resource_id, resource_type,
resource_type_display_name, map_id, map_name]))
conn3.commit()
cursor3.close()
conn3.close()
</code>
<code>import requests import random import json import string import time import pyodbc import textwrap #proxies: proxies = { 'http': 'http://proxy.me.com:3128', 'https': 'http://proxy.me.com:3128'} payload_login = json.dumps({ "un": "Admin", "passwd": "2020admin" }) headers_login = { 'Content-Type': 'application/json', 'Accept': 'application/json' } #login_request: url = "http://api.testing/login" session = requests.Session() session.verify = False response = requests.request("POST", url, headers=headers_login, data=payload_login,proxies=proxies) assert response.status_code == 200 json_data = response.json() json_str = json.dumps(json_data, indent=4) auth_token = json_data["access_token"] print("Bearer "+auth_token) auth_token2 = "Bearer " + auth_token response.close() time.sleep(1) #return auth_token with open(r'C:\Credentials\credentials.json', 'r') as json_file: credentials = json.load(json_file) credentials1 = credentials['CloudP'] conn_str1 = ( f"DRIVER=SQL Server;" f"SERVER={credentials1['host']};" f"DATABASE={credentials1['database_name']};" f"UID={credentials1['username']};" f"PWD={credentials1['password']};" "ENCRYPT=no" ) conn1 = pyodbc.connect(conn_str1, timeout=100) cursor1 = conn1.cursor() next_headers_get = { 'Accept': 'application/json', 'Authorization': auth_token2 } url2 = "http://api.testing/proddetail" response3 = requests.request("GET", url2, headers=next_headers_get,proxies=proxies) #assert response2.status_code == 200 json_data3 = response3.json() json_str3 = json.dumps(json_data3, indent=4) insert_query3 = """ INSERT INTO dbo.proddetail.resources (ItemID, ResourceID, ResourceType, RST_DisplayName, MapID, MapName) VALUES (?, ?, ?, ?, ?, ?) """ for content in json_data3['content']: id = content['id'] resource_id = content['resourceId'] resource_type = content['resourceType'] resource_type_display_name = content['resourceTypeDisplayName'] map_id = content['location']['properties']['mapId'] map_name = content['location']['properties']['mapName'] cursor3.execute(insert_query3, ([id, resource_id, resource_type, resource_type_display_name, map_id, map_name])) conn3.commit() cursor3.close() conn3.close() </code>
import requests
import random
import json
import string
import time
import pyodbc
import textwrap

#proxies:
proxies = {
       'http': 'http://proxy.me.com:3128',
       'https': 'http://proxy.me.com:3128'}


payload_login = json.dumps({
  "un": "Admin",
  "passwd": "2020admin"
})

headers_login = {
  'Content-Type': 'application/json',
  'Accept': 'application/json'
}


#login_request:

url = "http://api.testing/login"
session = requests.Session()
session.verify = False
response = requests.request("POST", url, headers=headers_login, data=payload_login,proxies=proxies)
assert response.status_code == 200
json_data = response.json()
json_str = json.dumps(json_data, indent=4)
auth_token = json_data["access_token"]

print("Bearer "+auth_token)
auth_token2 = "Bearer " + auth_token
response.close()
time.sleep(1)
#return auth_token

with open(r'C:\Credentials\credentials.json', 'r') as json_file:
    credentials = json.load(json_file)
credentials1 = credentials['CloudP']
conn_str1 = (
    f"DRIVER=SQL Server;"
    f"SERVER={credentials1['host']};"
    f"DATABASE={credentials1['database_name']};"
    f"UID={credentials1['username']};"
    f"PWD={credentials1['password']};"
    "ENCRYPT=no"
)

conn1 = pyodbc.connect(conn_str1, timeout=100)  
cursor1 = conn1.cursor()

next_headers_get = {
  'Accept': 'application/json',
  'Authorization': auth_token2
}

url2 = "http://api.testing/proddetail"

response3 = requests.request("GET", url2, headers=next_headers_get,proxies=proxies)
#assert response2.status_code == 200
json_data3 = response3.json()
json_str3 = json.dumps(json_data3, indent=4)

insert_query3 = """
    INSERT INTO dbo.proddetail.resources (ItemID, ResourceID, ResourceType, RST_DisplayName, MapID, MapName)
    VALUES (?, ?, ?, ?, ?, ?)
    """
for content in json_data3['content']:
    id = content['id']
    resource_id = content['resourceId']
    resource_type = content['resourceType']
    resource_type_display_name = content['resourceTypeDisplayName']
    map_id = content['location']['properties']['mapId']
    map_name = content['location']['properties']['mapName']
    
    cursor3.execute(insert_query3, ([id, resource_id, resource_type, 
                                     resource_type_display_name, map_id, map_name]))
        
conn3.commit()
cursor3.close()
conn3.close()

Now, below is a sample of the JSON response.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> {
"content": [
{
"id": "647e2694781914b2c5b0f7c7",
"resourceId": "22874",
"resourceType": "1",
"resourceTypeDisplayName": "AC",
"location": {
"type": "Feature",
"properties": {
"mapId": "1",
"mapName": "Washington"
},
"geometry": {
"type": "point",
"coordinates": [
7532.0,
4600.0,
20.0
]
}
},
"gpsLocation": {
"type": "Feature",
"properties": {},
"geometry": {
"type": "point",
"coordinates": [
-85.96,
30.05,
0.0
]
}
},
"lastLocateTimestamp": "2023-02-05T15:14:41.010Z",
"blinkTimestamp": "2023-02-05T15:14:41.010Z",
"locateType": "BLINK",
"lastBlinkElapsedTime": 82,
"lastLocateElapsedTime": 82,
"creationTime": "2020-02-20T13:11:19.527Z",
"lastUpdateTime": "2021-10-27T03:50:56.500Z",
"site": {
"siteId": "5e4add52ef500a19a3634257",
"siteName": "Washington",
},
"customProperties": {},
"associatedTags": [
{
"tagId": "154",
"tagSource": "TRUTH",
"lastBlinkTimestamp": "2023-02-05T15:14:41.010Z"
}
],
"description": "2",
"alert": false,
"blinking": false,
"locating": false,
"batteryLow": false
},
}
</code>
<code> { "content": [ { "id": "647e2694781914b2c5b0f7c7", "resourceId": "22874", "resourceType": "1", "resourceTypeDisplayName": "AC", "location": { "type": "Feature", "properties": { "mapId": "1", "mapName": "Washington" }, "geometry": { "type": "point", "coordinates": [ 7532.0, 4600.0, 20.0 ] } }, "gpsLocation": { "type": "Feature", "properties": {}, "geometry": { "type": "point", "coordinates": [ -85.96, 30.05, 0.0 ] } }, "lastLocateTimestamp": "2023-02-05T15:14:41.010Z", "blinkTimestamp": "2023-02-05T15:14:41.010Z", "locateType": "BLINK", "lastBlinkElapsedTime": 82, "lastLocateElapsedTime": 82, "creationTime": "2020-02-20T13:11:19.527Z", "lastUpdateTime": "2021-10-27T03:50:56.500Z", "site": { "siteId": "5e4add52ef500a19a3634257", "siteName": "Washington", }, "customProperties": {}, "associatedTags": [ { "tagId": "154", "tagSource": "TRUTH", "lastBlinkTimestamp": "2023-02-05T15:14:41.010Z" } ], "description": "2", "alert": false, "blinking": false, "locating": false, "batteryLow": false }, } </code>
    {
    "content": [
        {
            "id": "647e2694781914b2c5b0f7c7",
            "resourceId": "22874",
            "resourceType": "1",
            "resourceTypeDisplayName": "AC",
            "location": {
                "type": "Feature",
                "properties": {
                    "mapId": "1",
                    "mapName": "Washington"
                },
                "geometry": {
                    "type": "point",
                    "coordinates": [
                        7532.0,
                        4600.0,
                        20.0
                    ]
                }
            },
            "gpsLocation": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "point",
                    "coordinates": [
                        -85.96,
                        30.05,
                        0.0
                    ]
                }
            },
            "lastLocateTimestamp": "2023-02-05T15:14:41.010Z",
            "blinkTimestamp": "2023-02-05T15:14:41.010Z",
            "locateType": "BLINK",
            "lastBlinkElapsedTime": 82,
            "lastLocateElapsedTime": 82,
            "creationTime": "2020-02-20T13:11:19.527Z",
            "lastUpdateTime": "2021-10-27T03:50:56.500Z",
            "site": {
                "siteId": "5e4add52ef500a19a3634257",
                "siteName": "Washington",
            },
            "customProperties": {},
            "associatedTags": [
                {
                    "tagId": "154",
                    "tagSource": "TRUTH",
                    "lastBlinkTimestamp": "2023-02-05T15:14:41.010Z"
                }
            ],
            "description": "2",
            "alert": false,
            "blinking": false,
            "locating": false,
            "batteryLow": false
        },
}

Here is the error I get:

Message=the JSON object must be str, bytes or bytearray, not dict

I’ve also tried assigning the values to variables in a for loop using this:

TestVAR = content.get(‘id’, ”)

this works but only on the first level items in the JSON.

I’ve been stuck for 2 days and I’d be greatly appreciative to anyone whom might know the fix for this? Thank you!!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật