In my code, I have a nested dictionary and I want to ensure that key id is an integer (note: it is a primary key). I tried just casting it to an int but I am unsure if the key is an int given that in the JSON there are double quotes.
See below my code and example of the data format.
statistics = defaultdict(dict)
\\in a loop
statistics[state][date].append({
int(id): {
"count_targets": targets,
"count_targets_excluded": excluded,
"count_targets_pending": pending,
"count_targets_in_progress": progress,
"count_targets_completed": completed,
"count_targets_failed": failed
}
})
{
"stateA": {
"2015-02-15": [
{
"13": {
"count_targets": 5,
"count_targets_excluded": 3,
"count_targets_pending": 3,
"count_targets_in_progress": 0,
"count_targets_completed": 1,
"count_targets_failed": 0
}
},
{
"14": {
"count_targets": 4,
"count_targets_excluded": 3,
"count_targets_pending": 3,
"count_targets_in_progress": 0,
"count_targets_completed": 1,
"count_targets_failed": 0
}
},
>Solution :
JSON objects can only use JSON strings as keys:
>>> json.dumps({3: 4})
'{"3": 4}'
While the key in you dict is certainly an int, it gets converted to a string when encoding as JSON. JSON itself doesn’t have a way of "remembering" the original type of the value used as a key, so you need some method (extra data in your JSON object, a pre-defined schema, etc) that the consumer of the JSON can use to turn the key back into an int after decoding.