I would like to sort these JSON objects by the key "vnet" in each range (eg. range1, range2) in python3.
I have been able to sort it like this:
source["range1"].sort(key=lambda x: x["vnet"])
But unfortunately it does not use any IP address logic and sorts it by char.
Unsorted example:
{
"range1": [
{
"name": "vnet1",
"vnet": "192.168.11.0/25",
"subnet": []
},
{
"name": "vnet2",
"vnet": "192.168.2.0/24",
"subnet": []
}
],
"range2": [
{
"name": "vnet3",
"vnet": "10.168.11.0/25",
"subnet": []
},
{
"name": "vnet4",
"vnet": "10.168.2.0/25",
"subnet": []
},
{
"name": "vnet5",
"vnet": "10.168.220.0/25",
"subnet": []
}
]
}
Sorted it should look like:
{
"range1": [
{
"name": "vnet2",
"vnet": "192.168.2.0/24",
"subnet": []
},
{
"name": "vnet1",
"vnet": "192.168.11.0/25",
"subnet": []
}
],
"range2": [
{
"name": "vnet4",
"vnet": "10.168.2.0/25",
"subnet": []
},
{
"name": "vnet3",
"vnet": "10.168.11.0/25",
"subnet": []
},
{
"name": "vnet5",
"vnet": "10.168.220.0/25",
"subnet": []
}
]
}
I would very much appreciate any help on this, since I am stuck here right now.
CodePudding user response:
Assuming you have your dict stored in json_dict
.
You can use socket.inet_aton(__ip_string: str)
as a key to sorting function. It will convert ip string to 32-bit packed binary.
So the following code will do what you want
import socket
json_dict = {
"range1": [
{
"name": "vnet1",
"vnet": "192.168.11.0/25",
"subnet": []
},
{
"name": "vnet2",
"vnet": "192.168.2.0/24",
"subnet": []
}
],
"range2": [
{
"name": "vnet3",
"vnet": "10.168.11.0/25",
"subnet": []
},
{
"name": "vnet4",
"vnet": "10.168.2.0/25",
"subnet": []
},
{
"name": "vnet5",
"vnet": "10.168.220.0/25",
"subnet": []
}
]
}
for key, value in json_dict.items():
value.sort(key=lambda x: socket.inet_aton(x['vnet'].split("/")[0]))
print(json_dict)