Sidharth kaushik
Sidharth kaushik

Reputation: 257

Dict type is not hashable in case of Json, tried sets as well

I am doing a project for my school. I am trying to convert a dict to json, so i can post it as a json request.

Here's the sample dict which i am trying to get as json.

dict = {
        {'subject': 'testing123',
         'start': {
             'dateTime': "2020-06-13T21:30:02.096Z",
             "timezone": "UTC"},
         'end': {
             'dateTime': "2020-06-20T21:30:02.096Z",
             'timezone': 'UTC'}
         }
    }

I tried first normally by loading it in json but failed by error 'timezone': 'UTC' is not serilizable.

so i checked on google and then i tried to dump it in json and load it in up in json as variable. i.e

dict_json = json.dumps(dict)
dict_json = json.loads(dict)
print(dict_json)

but again got the hashing error.

then i tried to search on google again and found out i have to convert them to tuple if i have multiple dictionaries not sure on this one though if this is a right finding.

dict = {
        tuple({'subject': 'testing123',
         'start': tuple({
             'dateTime': "2020-06-13T21:30:02.096Z",
             "timezone": "UTC"}),
         'end': tuple({
             'dateTime': "2020-06-20T21:30:02.096Z",
             'timezone': 'UTC'})
         })
    }

then it became a set and set is also not Json serializable now, ran out of options. Need suggestion on this problem to convert this dict into a valid json format.

Upvotes: -2

Views: 308

Answers (1)

pythomatic
pythomatic

Reputation: 657

Remove the word tuple and the parentheses that go with it. Next every entry in the dict must have a key and a value. The first level of your dict does not have a pair like that. Here is what I believe to be your intended object:

dict = {
           'subject': 'testing123',
           'start': {
               'dateTime': "2020-06-13T21:30:02.096Z",
               'timezone': 'UTC'},
           'end': {
               'dateTime': "2020-06-20T21:30:02.096Z",
               'timezone': 'UTC'}
        }

here is the result of performing your test case on this object:

>>> dict = {
...            'subject': 'testing123',
...            'start': {
...                'dateTime': "2020-06-13T21:30:02.096Z",
...                'timezone': 'UTC'},
...            'end': {
...                'dateTime': "2020-06-20T21:30:02.096Z",
...                'timezone': 'UTC'}
...         }
>>> json_dict = json.dumps(dict)
>>> dict_from_json = json.loads(json_dict)
>>> dict_from_json
{'subject': 'testing123', 'start': {'dateTime': '2020-06-13T21:30:02.096Z', 'timezone': 'UTC'}, 'end': {'dateTime': '2020-06-20T21:30:02.096Z', 'timezone': 'UTC'}}
>>> dict_from_json['subject']
'testing123'

Upvotes: 1

Related Questions