Python 从RESTAPI GET创建嵌套json格式
问题: 从RESTAPI GET存储的值创建json数据结构 问题: 动态创建嵌套数据结构 用于检索值的Python代码: 所需的数据结构输出。Python 从RESTAPI GET创建嵌套json格式,python,json,rest,Python,Json,Rest,问题: 从RESTAPI GET存储的值创建json数据结构 问题: 动态创建嵌套数据结构 用于检索值的Python代码: 所需的数据结构输出。 您可以按如下方式更新客户端词典: clients = [] for data in resp['queryResponse']['entity'] : clientID = data.get("clientDetailsDTO", {}).get("@id") associationTime = data.get("clientDet
您可以按如下方式更新客户端词典:
clients = []
for data in resp['queryResponse']['entity'] :
clientID = data.get("clientDetailsDTO", {}).get("@id")
associationTime = data.get("clientDetailsDTO", {}).get("associationTime")
clientInterface = data.get("clientDetailsDTO", {}).get("clientInterface")
connectionType = data.get("clientDetailsDTO", {}).get("connectionType")
deviceIpAddress = data.get("clientDetailsDTO", {}).get("deviceIpAddress")
deviceName = data.get("clientDetailsDTO", {}).get("deviceName")
firstSeenTime = data.get("clientDetailsDTO", {}).get("firstSeenTime")
ifIndex = data.get("clientDetailsDTO", {}).get("ifIndex")
ipAddress = data.get("clientDetailsDTO", {}).get("ipAddress")
macAddress = data.get("clientDetailsDTO", {}).get("macAddress")
updateTime = data.get("clientDetailsDTO", {}).get("updateTime")
vendor = data.get("clientDetailsDTO", {}).get("vendor")
vlan = data.get("clientDetailsDTO", {}).get("vlan")
vlanName = data.get("clientDetailsDTO", {}).get("vlanName")
clients.append({
'ClientID' : clientID,
'value' :
{
'associationTime' : associationTime,
'vlanName' : vlanName,
'connectionType' : connectionType
}
})
json.dumps(clients)
下面的代码符合您的要求。它找到id字段,然后遍历所有键并将它们添加到dict中,将id:{values}添加到主dict中,最后打印 导入json
my_response = {"queryResponse": {"@responseType": "listEntityInstances", "@count": 192077, "@last": 1,
"@rootUrl": "https://ciscoprime.com/webacs/api/v2/data",
"@requestUrl": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails?.nocount=True&.maxResults=2&.firstResult=0&.full=true",
"entity": [{"clientDetailsDTO": {"apName": "nzcfd-rotooff-ap2", "deviceName": "cntl-1",
"updateTime": 1490290426910,
"protocol": "DOT11N2_4GNZ",
"clientInterface": "management",
"macAddress": "FF:FF:FF:FF:FF:FF",
"ccxLSVersion": "V1", "policyTypeStatus": "NOMETHOD",
"wgbMacAddress": "00:00:00:00:00:00",
"wepState": "DISABLED", "ccxVersion": "UNSUPPORTED",
"speed": "UNKNOWN", "@displayName": "4110106",
"hreapLocallyAuthenticated": "2", "ssid": "Guest",
"clientAaaOverrideAclApplied": "NA",
"ccxVSVersion": "V1",
"securityPolicyStatus": "FAILED",
"authenticationAlgorithm": "OPENSYSTEM",
"connectionType": "LIGHTWEIGHTWIRELESS",
"postureStatus": "UNKNOWN", "deviceType": "none",
"location": "Root Area", "wiredClientType": "NA",
"status": "ASSOCIATED",
"firstSeenTime": 1487771895967,
"wgbStatus": "REGULARCLIENT",
"vendor": "Samsung Electronics", "vlan": "10",
"ccxMSVersion": "V1", "nacState": "ACCESS",
"webSecurity": "DISABLED", "policyType": "NA",
"associationTime": 1488178285705, "ifIndex": 0,
"apIpAddress": {"address": "1.2.2.2"}, "@id": 4110106,
"eapType": "UNNOWN",
"mobilityStatus": "EXPORTANCHORED", "ipType": "IPV4",
"ipAddress": {"address": "10.2.2.2"}, "apSlotId": 0,
"encryptionCypher": "NONE",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxFSVersion": "V1", "clientApMode": "UNKNOWN",
"deviceIpAddress": {"address": "172.2.2.2"},
"clientAclApplied": "NA"},
"@url": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails/4110106",
"@type": "ClientDetails", "@dtoType": "clientDetailsDTO"},
{"clientDetailsDTO": {"apName": "nzcfd-rotooff-ap2", "deviceName": "cntl-1",
"updateTime": 1490290426910,
"protocol": "DOT11N2_4GNZ",
"clientInterface": "management",
"macAddress": "FF:FF:FF:FF:FF:FF",
"ccxLSVersion": "V1", "policyTypeStatus": "NOMETHOD",
"wgbMacAddress": "00:00:00:00:00:00",
"wepState": "DISABLED", "ccxVersion": "UNSUPPORTED",
"speed": "UNKNOWN", "@displayName": "4110106",
"hreapLocallyAuthenticated": "2", "ssid": "Guest",
"clientAaaOverrideAclApplied": "NA",
"ccxVSVersion": "V1",
"securityPolicyStatus": "FAILED",
"authenticationAlgorithm": "OPENSYSTEM",
"connectionType": "LIGHTWEIGHTWIRELESS",
"postureStatus": "UNKNOWN", "deviceType": "none",
"location": "Root Area", "wiredClientType": "NA",
"status": "ASSOCIATED",
"firstSeenTime": 1487771895967,
"wgbStatus": "REGULARCLIENT",
"vendor": "Samsung Electronics", "vlan": "10",
"ccxMSVersion": "V1", "nacState": "ACCESS",
"webSecurity": "DISABLED", "policyType": "NA",
"associationTime": 1488178285705, "ifIndex": 0,
"apIpAddress": {"address": "1.2.2.2"}, "@id": 4110107,
"eapType": "UNNOWN",
"mobilityStatus": "EXPORTANCHORED", "ipType": "IPV4",
"ipAddress": {"address": "10.2.2.2"}, "apSlotId": 0,
"encryptionCypher": "NONE",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxFSVersion": "V1", "clientApMode": "UNKNOWN",
"deviceIpAddress": {"address": "172.2.2.2"},
"clientAclApplied": "NA"},
"@url": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails/4110106",
"@type": "ClientDetails", "@dtoType": "clientDetailsDTO"}]}}
clientlist = my_response['queryResponse'].get('entity', [])
# Initialize my empty dict
formatted_clients = {}
if clientlist:
for client in clientlist:
# Initialize an empty client dict.
client_dict = {}
# Validate clientDetailsDTO
if "clientDetailsDTO" in client:
client_id = client['clientDetailsDTO'].get('@id', '')
if not client_id:
# Let's bail out if this doesn't exist
continue
for key in client['clientDetailsDTO'].keys():
# iterate through the keys, and add them to the client dict
if key == "@id":
# we don't need the client id key inside the dict
continue
client_dict[key] = client['clientDetailsDTO'][key]
# append the client_dict to formatted list
formatted_clients[client_id] = client_dict
print(json.dumps(formatted_clients, indent=4))
结果:
{
"4110106": {
"firstSeenTime": 1487771895967,
"status": "ASSOCIATED",
"@displayName": "4110106",
"clientAaaOverrideAclApplied": "NA",
"mobilityStatus": "EXPORTANCHORED",
"ccxFSVersion": "V1",
"deviceType": "none",
"ccxMSVersion": "V1",
"speed": "UNKNOWN",
"location": "Root Area",
"ipType": "IPV4",
"wepState": "DISABLED",
"eapType": "UNNOWN",
"wiredClientType": "NA",
"hreapLocallyAuthenticated": "2",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxVersion": "UNSUPPORTED",
"webSecurity": "DISABLED",
"wgbMacAddress": "00:00:00:00:00:00",
"encryptionCypher": "NONE",
"nacState": "ACCESS",
"macAddress": "FF:FF:FF:FF:FF:FF",
"securityPolicyStatus": "FAILED",
"ssid": "Guest",
"deviceIpAddress": {
"address": "172.2.2.2"
},
"clientAclApplied": "NA",
"ccxVSVersion": "V1",
"ifIndex": 0,
"clientApMode": "UNKNOWN",
"apIpAddress": {
"address": "1.2.2.2"
},
"connectionType": "LIGHTWEIGHTWIRELESS",
"vlan": "10",
"ccxLSVersion": "V1",
"apSlotId": 0,
"clientInterface": "management",
"protocol": "DOT11N2_4GNZ",
"authenticationAlgorithm": "OPENSYSTEM",
"vendor": "Samsung Electronics",
"updateTime": 1490290426910,
"deviceName": "cntl-1",
"apName": "nzcfd-rotooff-ap2",
"ipAddress": {
"address": "10.2.2.2"
},
"wgbStatus": "REGULARCLIENT",
"postureStatus": "UNKNOWN",
"policyTypeStatus": "NOMETHOD",
"associationTime": 1488178285705,
"policyType": "NA"
},
"4110107": {
"firstSeenTime": 1487771895967,
"status": "ASSOCIATED",
"@displayName": "4110106",
"clientAaaOverrideAclApplied": "NA",
"mobilityStatus": "EXPORTANCHORED",
"ccxFSVersion": "V1",
"deviceType": "none",
"ccxMSVersion": "V1",
"speed": "UNKNOWN",
"location": "Root Area",
"ipType": "IPV4",
"wepState": "DISABLED",
"eapType": "UNNOWN",
"wiredClientType": "NA",
"hreapLocallyAuthenticated": "2",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxVersion": "UNSUPPORTED",
"webSecurity": "DISABLED",
"wgbMacAddress": "00:00:00:00:00:00",
"encryptionCypher": "NONE",
"nacState": "ACCESS",
"macAddress": "FF:FF:FF:FF:FF:FF",
"securityPolicyStatus": "FAILED",
"ssid": "Guest",
"deviceIpAddress": {
"address": "172.2.2.2"
},
"clientAclApplied": "NA",
"ccxVSVersion": "V1",
"ifIndex": 0,
"clientApMode": "UNKNOWN",
"apIpAddress": {
"address": "1.2.2.2"
},
"connectionType": "LIGHTWEIGHTWIRELESS",
"vlan": "10",
"ccxLSVersion": "V1",
"apSlotId": 0,
"clientInterface": "management",
"protocol": "DOT11N2_4GNZ",
"authenticationAlgorithm": "OPENSYSTEM",
"vendor": "Samsung Electronics",
"updateTime": 1490290426910,
"deviceName": "cntl-1",
"apName": "nzcfd-rotooff-ap2",
"ipAddress": {
"address": "10.2.2.2"
},
"wgbStatus": "REGULARCLIENT",
"postureStatus": "UNKNOWN",
"policyTypeStatus": "NOMETHOD",
"associationTime": 1488178285705,
"policyType": "NA"
}
}
在您确切的上下文中,此代码将用于您想要的字段:
import json
import requests
url = 'https://ciscoprime.com/webacs/api/v2/data/ClientDetails.json?.nocount=True&.maxResults=2&.firstResult=0&.full=true'
get_response = requests.get(url, verify=False)
response = json.dumps(get_response.json())
resp = json.loads(response)
clientlist = resp['queryResponse'].get('entity', [])
# Initialize my empty dict
formatted_clients = {}
search_keys = ["associationTime", "clientInterface", "connectionType", "deviceIpAddress", "deviceName", "firstSeenTime", "macAddress", "updateTime", "vendor", "vlan", "vlanName"]
if clientlist:
for client in clientlist:
# Initialize an empty client dict.
client_dict = {}
# Validate clientDetailsDTO
if "clientDetailsDTO" in client:
client_id = client['clientDetailsDTO'].get('@id', '')
if not client_id:
# Let's bail out if this doesn't exist
continue
for key in client['clientDetailsDTO'].keys():
# iterate through the keys, and add them to the client dict
if key in search_keys:
client_dict[key] = client['clientDetailsDTO'][key]
# append the client_dict to formatted list
formatted_clients[client_id] = client_dict
print(json.dumps(formatted_clients, indent=4))
您需要提供API GET请求中json返回数据的格式。我已使用请求的信息更新了问题您所需的数据结构输出不是json。我已删除该要求,因为它与此无关@satishgarg您拥有的json:clientID:value{stuff}无效。所以你不能这么做。但是您可以将实际的客户机id作为dictionary对象的键。这就是我最初打算做的,但是dictionary会被覆盖。所以,如果我在所有的身份中循环,那么对于测试,我只做了两个。它只在被覆盖时执行最后一个操作。我显然需要把这部分从循环中去掉,但我仍在学习,所以我还不确定如何做到这一点。这也没有遵循我正在寻找的数据结构。首先,客户端字典被声明为在循环之外,这样它的数据就不会被覆盖。其次,您不需要显式地使用i和for循环。这看起来很棒,应该可以工作。但是我从第24行或第25行得到一个语法错误,但是语法看起来是正确的。具体的回溯是什么?#python primeapi2.py文件“primeapi2.py”,第25行}^语法错误:无效语法
my_response = {"queryResponse": {"@responseType": "listEntityInstances", "@count": 192077, "@last": 1,
"@rootUrl": "https://ciscoprime.com/webacs/api/v2/data",
"@requestUrl": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails?.nocount=True&.maxResults=2&.firstResult=0&.full=true",
"entity": [{"clientDetailsDTO": {"apName": "nzcfd-rotooff-ap2", "deviceName": "cntl-1",
"updateTime": 1490290426910,
"protocol": "DOT11N2_4GNZ",
"clientInterface": "management",
"macAddress": "FF:FF:FF:FF:FF:FF",
"ccxLSVersion": "V1", "policyTypeStatus": "NOMETHOD",
"wgbMacAddress": "00:00:00:00:00:00",
"wepState": "DISABLED", "ccxVersion": "UNSUPPORTED",
"speed": "UNKNOWN", "@displayName": "4110106",
"hreapLocallyAuthenticated": "2", "ssid": "Guest",
"clientAaaOverrideAclApplied": "NA",
"ccxVSVersion": "V1",
"securityPolicyStatus": "FAILED",
"authenticationAlgorithm": "OPENSYSTEM",
"connectionType": "LIGHTWEIGHTWIRELESS",
"postureStatus": "UNKNOWN", "deviceType": "none",
"location": "Root Area", "wiredClientType": "NA",
"status": "ASSOCIATED",
"firstSeenTime": 1487771895967,
"wgbStatus": "REGULARCLIENT",
"vendor": "Samsung Electronics", "vlan": "10",
"ccxMSVersion": "V1", "nacState": "ACCESS",
"webSecurity": "DISABLED", "policyType": "NA",
"associationTime": 1488178285705, "ifIndex": 0,
"apIpAddress": {"address": "1.2.2.2"}, "@id": 4110106,
"eapType": "UNNOWN",
"mobilityStatus": "EXPORTANCHORED", "ipType": "IPV4",
"ipAddress": {"address": "10.2.2.2"}, "apSlotId": 0,
"encryptionCypher": "NONE",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxFSVersion": "V1", "clientApMode": "UNKNOWN",
"deviceIpAddress": {"address": "172.2.2.2"},
"clientAclApplied": "NA"},
"@url": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails/4110106",
"@type": "ClientDetails", "@dtoType": "clientDetailsDTO"},
{"clientDetailsDTO": {"apName": "nzcfd-rotooff-ap2", "deviceName": "cntl-1",
"updateTime": 1490290426910,
"protocol": "DOT11N2_4GNZ",
"clientInterface": "management",
"macAddress": "FF:FF:FF:FF:FF:FF",
"ccxLSVersion": "V1", "policyTypeStatus": "NOMETHOD",
"wgbMacAddress": "00:00:00:00:00:00",
"wepState": "DISABLED", "ccxVersion": "UNSUPPORTED",
"speed": "UNKNOWN", "@displayName": "4110106",
"hreapLocallyAuthenticated": "2", "ssid": "Guest",
"clientAaaOverrideAclApplied": "NA",
"ccxVSVersion": "V1",
"securityPolicyStatus": "FAILED",
"authenticationAlgorithm": "OPENSYSTEM",
"connectionType": "LIGHTWEIGHTWIRELESS",
"postureStatus": "UNKNOWN", "deviceType": "none",
"location": "Root Area", "wiredClientType": "NA",
"status": "ASSOCIATED",
"firstSeenTime": 1487771895967,
"wgbStatus": "REGULARCLIENT",
"vendor": "Samsung Electronics", "vlan": "10",
"ccxMSVersion": "V1", "nacState": "ACCESS",
"webSecurity": "DISABLED", "policyType": "NA",
"associationTime": 1488178285705, "ifIndex": 0,
"apIpAddress": {"address": "1.2.2.2"}, "@id": 4110107,
"eapType": "UNNOWN",
"mobilityStatus": "EXPORTANCHORED", "ipType": "IPV4",
"ipAddress": {"address": "10.2.2.2"}, "apSlotId": 0,
"encryptionCypher": "NONE",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxFSVersion": "V1", "clientApMode": "UNKNOWN",
"deviceIpAddress": {"address": "172.2.2.2"},
"clientAclApplied": "NA"},
"@url": "https://ciscoprime.com/webacs/api/v2/data/ClientDetails/4110106",
"@type": "ClientDetails", "@dtoType": "clientDetailsDTO"}]}}
clientlist = my_response['queryResponse'].get('entity', [])
# Initialize my empty dict
formatted_clients = {}
if clientlist:
for client in clientlist:
# Initialize an empty client dict.
client_dict = {}
# Validate clientDetailsDTO
if "clientDetailsDTO" in client:
client_id = client['clientDetailsDTO'].get('@id', '')
if not client_id:
# Let's bail out if this doesn't exist
continue
for key in client['clientDetailsDTO'].keys():
# iterate through the keys, and add them to the client dict
if key == "@id":
# we don't need the client id key inside the dict
continue
client_dict[key] = client['clientDetailsDTO'][key]
# append the client_dict to formatted list
formatted_clients[client_id] = client_dict
print(json.dumps(formatted_clients, indent=4))
{
"4110106": {
"firstSeenTime": 1487771895967,
"status": "ASSOCIATED",
"@displayName": "4110106",
"clientAaaOverrideAclApplied": "NA",
"mobilityStatus": "EXPORTANCHORED",
"ccxFSVersion": "V1",
"deviceType": "none",
"ccxMSVersion": "V1",
"speed": "UNKNOWN",
"location": "Root Area",
"ipType": "IPV4",
"wepState": "DISABLED",
"eapType": "UNNOWN",
"wiredClientType": "NA",
"hreapLocallyAuthenticated": "2",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxVersion": "UNSUPPORTED",
"webSecurity": "DISABLED",
"wgbMacAddress": "00:00:00:00:00:00",
"encryptionCypher": "NONE",
"nacState": "ACCESS",
"macAddress": "FF:FF:FF:FF:FF:FF",
"securityPolicyStatus": "FAILED",
"ssid": "Guest",
"deviceIpAddress": {
"address": "172.2.2.2"
},
"clientAclApplied": "NA",
"ccxVSVersion": "V1",
"ifIndex": 0,
"clientApMode": "UNKNOWN",
"apIpAddress": {
"address": "1.2.2.2"
},
"connectionType": "LIGHTWEIGHTWIRELESS",
"vlan": "10",
"ccxLSVersion": "V1",
"apSlotId": 0,
"clientInterface": "management",
"protocol": "DOT11N2_4GNZ",
"authenticationAlgorithm": "OPENSYSTEM",
"vendor": "Samsung Electronics",
"updateTime": 1490290426910,
"deviceName": "cntl-1",
"apName": "nzcfd-rotooff-ap2",
"ipAddress": {
"address": "10.2.2.2"
},
"wgbStatus": "REGULARCLIENT",
"postureStatus": "UNKNOWN",
"policyTypeStatus": "NOMETHOD",
"associationTime": 1488178285705,
"policyType": "NA"
},
"4110107": {
"firstSeenTime": 1487771895967,
"status": "ASSOCIATED",
"@displayName": "4110106",
"clientAaaOverrideAclApplied": "NA",
"mobilityStatus": "EXPORTANCHORED",
"ccxFSVersion": "V1",
"deviceType": "none",
"ccxMSVersion": "V1",
"speed": "UNKNOWN",
"location": "Root Area",
"ipType": "IPV4",
"wepState": "DISABLED",
"eapType": "UNNOWN",
"wiredClientType": "NA",
"hreapLocallyAuthenticated": "2",
"apMacAddress": "FF:FF:FF:FF:FF:FF",
"ccxVersion": "UNSUPPORTED",
"webSecurity": "DISABLED",
"wgbMacAddress": "00:00:00:00:00:00",
"encryptionCypher": "NONE",
"nacState": "ACCESS",
"macAddress": "FF:FF:FF:FF:FF:FF",
"securityPolicyStatus": "FAILED",
"ssid": "Guest",
"deviceIpAddress": {
"address": "172.2.2.2"
},
"clientAclApplied": "NA",
"ccxVSVersion": "V1",
"ifIndex": 0,
"clientApMode": "UNKNOWN",
"apIpAddress": {
"address": "1.2.2.2"
},
"connectionType": "LIGHTWEIGHTWIRELESS",
"vlan": "10",
"ccxLSVersion": "V1",
"apSlotId": 0,
"clientInterface": "management",
"protocol": "DOT11N2_4GNZ",
"authenticationAlgorithm": "OPENSYSTEM",
"vendor": "Samsung Electronics",
"updateTime": 1490290426910,
"deviceName": "cntl-1",
"apName": "nzcfd-rotooff-ap2",
"ipAddress": {
"address": "10.2.2.2"
},
"wgbStatus": "REGULARCLIENT",
"postureStatus": "UNKNOWN",
"policyTypeStatus": "NOMETHOD",
"associationTime": 1488178285705,
"policyType": "NA"
}
}
import json
import requests
url = 'https://ciscoprime.com/webacs/api/v2/data/ClientDetails.json?.nocount=True&.maxResults=2&.firstResult=0&.full=true'
get_response = requests.get(url, verify=False)
response = json.dumps(get_response.json())
resp = json.loads(response)
clientlist = resp['queryResponse'].get('entity', [])
# Initialize my empty dict
formatted_clients = {}
search_keys = ["associationTime", "clientInterface", "connectionType", "deviceIpAddress", "deviceName", "firstSeenTime", "macAddress", "updateTime", "vendor", "vlan", "vlanName"]
if clientlist:
for client in clientlist:
# Initialize an empty client dict.
client_dict = {}
# Validate clientDetailsDTO
if "clientDetailsDTO" in client:
client_id = client['clientDetailsDTO'].get('@id', '')
if not client_id:
# Let's bail out if this doesn't exist
continue
for key in client['clientDetailsDTO'].keys():
# iterate through the keys, and add them to the client dict
if key in search_keys:
client_dict[key] = client['clientDetailsDTO'][key]
# append the client_dict to formatted list
formatted_clients[client_id] = client_dict
print(json.dumps(formatted_clients, indent=4))