21 Apr 2013 How JSON bites?

I like JSON. I really do. Sorry, Tom Preston-Werner. Therefore, it's no surprise I've used it in td as a persistent storage.

But sometimes even the technology you like and use - almost - everyday, bites in the least expected moment.

I've been using td like usual (yes, I sometimes use my software :-)), refining pacmixer's ToDo list, when I realised that it doesn't sort my items like it should. I needed it, so I immediately sat back and checked td's code for a cause.

To see what it turned out to be, consider this simple example.

1
2
3
4
5
6
import json


simple_dict = {1: 1}
jsonified = json.dumps(simple_dict)
unjsonified = json.loads(json)

What will the unjsonified variable hold? {1: 1}? Well, not really. It will be {'1': 1}.

Why? Because keys in JSON dictionaries are strings. Always. Period.

But I do want my integer keys! All internal functions work on integer indexes and only loading JSON from file breaks this routine.

So, I had to hack it a bit and take whatever key is available, like this.

1
value = unjsonified.get(1) or unjsonified.get("1")

Who would have predicted this... Maybe it is time to read the JSON specification :-).