-1

In the code below, why is the 1 key of people dictionary retrieved as string in session_retrieve view? How can I keep the original (integer) type?

Also, why does the same not happen for the 45 value?

def session_add(request):
    people = {
        1: {
            'name': 'Tom',
            'age': 45,
        }   
    }
    request.session['people'] = people
    print(request.session['people'])
    # prints {1: {'name': 'Tom', 'age': 45}}
    return HttpResponse('added')

def session_retrieve(request):
    print(request.session['people'])
    # prints {'1': {'name': 'Tom', 'age': 45}}
    return HttpResponse('retrieved')
barciewicz
  • 3,511
  • 6
  • 32
  • 72

2 Answers2

1

This behaviour is already mentioned in the documentation. Taking an example from the documentation

>>> # initial assignment
>>> request.session[0] = 'bar'
>>> # subsequent requests following serialization & deserialization
>>> # of session data
>>> request.session[0]  # KeyError
>>> request.session['0']
'bar'

Also, why does the same not happen for the 45 value?

JSON supports only string keys, but values can be anything.

Raj
  • 664
  • 4
  • 16
0

It's for JSON compatibility. Since keys are in essence attributes of a JavaScript object, they are strings. Fields can be any primitive or another object, so 45 remains a number.

Why JSON allows only string to be a key?