I'm trying to compare two complex json strings using python but I'm having some issues. The two strings I have are the same, but some fields of child elements appear in different orders.
EG:
a = """
{
"sgroupname":"windows_securezone",
"ipperms":[
{
"IpProtocol":"-1",
"IpRanges":[
{
"CidrIp":"194.66.78.xx/32"
},
{
"CidrIp":"86.17.73.xx/32"
}
],
"UserIdGroupPairs":[
],
"PrefixListIds":[
]
}
]
}
"""
b = """
{
"sgroupname":"windows_securezone",
"ipperms":[
{
"IpProtocol":"-1",
"IpRanges":[
{
"CidrIp":"86.17.73.xx/32"
},
{
"CidrIp":"194.66.78.xx/32"
}
],
"UserIdGroupPairs":[
],
"PrefixListIds":[
]
}
]
}
"""
The fact that the IpRanges list under the ipperms element returns in a different order seems to break the comparison; if I switch them to the same order the comparison works correctly.
I've tried using OrderedDict, the json.dumps 'sort_keys=True' parameter, and using the sorted() function, but I can't get the strings to compare. Any ideas?
Any help would be greatly appreciated!
sort_keysisn't going to help you becauseIpRangesis a list. It already has an ordering. If you wanted to compare these, you would need to sort any lists contained in your objects first...which is going to be tricky, since the members of those lists are dicts, which are not inherently sortable.json.loadsand just do plain equality tests? Also, what larsks said. :-)