我有一個 API,在呼叫它之后我得到了一個非常大的 json 作為回應。我想訪問嵌套字典中存在的類似鍵。我正在使用以下幾行來發出獲取請求并存盤 json 資料:-
p25_st_devices = r'https://url_from_where_im_getting_data.com'
header_events = {
'Authorization': 'Basic random_keys'}
r2 = requests.get(p25_st_devices, headers= header_events)
r2_json = json.loads(r2.content)
json的樣本如下: -
{
"next": "value",
"self": "value",
"managedObjects": [
{
"creationTime": "2021-08-02T10:48:15.120Z",
"type": " c8y_MQTTdevice",
"lastUpdated": "2022-03-24T17:09:01.240 03:00",
"childAdditions": {
"self": "value",
"references": []
},
"name": "PS_MQTT1",
"assetParents": {
"self": "value",
"references": []
},
"self": "value",
"id": "338",
"Building": "value"
},
{
"creationTime": "2021-08-02T13:06:09.834Z",
"type": " c8y_MQTTdevice",
"lastUpdated": "2021-12-27T12:08:20.186 03:00",
"childAdditions": {
"self": "value",
"references": []
},
"name": "FS_MQTT2",
"assetParents": {
"self": "value",
"references": []
},
"self": "value",
"id": "339",
"c8y_IsDevice": {}
},
{
"creationTime": "2021-08-02T13:06:39.602Z",
"type": " c8y_MQTTdevice",
"lastUpdated": "2021-12-27T12:08:20.433 03:00",
"childAdditions": {
"self": "value",
"references": []
},
"name": "PS_MQTT3",
"assetParents": {
"self": "value",
"references": []
},
"self": "value",
"id": "340",
"c8y_IsDevice": {}
}
],
"statistics": {
"totalPages": 423,
"currentPage": 1,
"pageSize": 3
}
}
根據我的理解,我可以使用訪問name密鑰r2_json['managedObjects'][0]['name']
但是我如何遍歷這個 json 并將所有值存盤name在一個陣列中?
編輯 1:
我試圖實作的另一件事是從 JSON 資料中獲取所有內容并將其存盤在嵌套 dict 僅包含開頭id的陣列中。因此,預期的輸出將是 device_id = ['338','340']managedObjectsnamePS_
uj5u.com熱心網友回復:
你不應該只呼叫[0]串列的索引,而是回圈它:
all_names = []
for object in r2_json['managedObjects']:
all_names.append(object['name'])
print(all_names)
編輯:OP更新他們的答案后更新答案。
對于您的第二個問題,您可以使用startswith(). 代碼幾乎相同。
PS_names = []
for object in r2_json['managedObjects']:
if object['name'].startswith("PS_"):
PS_names.append(object['id']) # we append with the id, if startswith("PS_") returns True.
print(PS_names)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/455997.html
標籤:Python 数组 json python-3.x 字典
