I need to parse a json file which unfortunately for me, does not follow the prototype. I have two issues with the data, but i've already found a workaround for it so i'll just mention it at the end, maybe someone can help there as well.
So i need to parse entries like this:
"Test":{
"entry":{
"Type":"Something"
},
"entry":{
"Type":"Something_Else"
}
}, ...
The json default parser updates the dictionary and therfore uses only the last entry. I HAVE to somehow store the other one as well, and i have no idea how to do this. I also HAVE to store the keys in the several dictionaries in the same order they appear in the file, thats why i am using an OrderedDict to do so. it works fine, so if there is any way to expand this with the duplicate entries i'd be grateful.
My second issue is that this very same json file contains entries like that:
"Test":{
{
"Type":"Something"
}
}
Json.load() function raises an exception when it reaches that line in the json file. The only way i worked around this was to manually remove the inner brackets myself.
Thanks in advance
You can use
JSONDecoder.object_pairs_hook
to customize howJSONDecoder
decodes objects. This hook function will be passed a list of(key, value)
pairs that you usually do some processing on, and then turn into adict
.However, since Python dictionaries don't allow for duplicate keys (and you simply can't change that), you can return the pairs unchanged in the hook and get a nested list of
(key, value)
pairs when you decode your JSON:Output:
How you use this data structure is up to you. As stated above, Python dictionaries won't allow for duplicate keys, and there's no way around that. How would you even do a lookup based on a key?
dct[key]
would be ambiguous.So you can either implement your own logic to handle a lookup the way you expect it to work, or implement some sort of collision avoidance to make keys unique if they're not, and then create a dictionary from your nested list.
Edit: Since you said you would like to modify the duplicate key to make it unique, here's how you'd do that:
Output:
The
make_unique
function is responsible for returning a collision-free key. In this example it just suffixes the key with_n
wheren
is an incremental counter - just adapt it to your needs.Because the
object_pairs_hook
receives the pairs exactly in the order they appear in the JSON document, it's also possible to preserve that order by using anOrderedDict
, I included that as well.Thanks a lot @Lukas Graf, i got it working as well by implementing my own version of the hook function
Only thing remaining is to automatically get rid of the double brackets and i am done :D Thanks again