0

i'm trying to pass the below list to ajax response but i'm getting below error

remove_duplicates = [{**l[0], 'record_id': set([x['record_id'] for x in l])} if len(l:=list(v)) > 1 else l[0] for _, v in groupby(sorted(list_of_dict, key=func), key=func)]

i'm using set to remove the duplicate record ids

list_of_dicts = [{'f_note':'text','record_id':{4691}},{'f_note':'sample','record_id':{4692}}]

return jsonify(list_of_dicts )

object of type set is not JSON serializable

please suggest me with the better option.

sruthi
  • 163
  • 9
  • 1
    why do you need the set, e.g. `{4691}` in the first place? suggest me better option - use different data structure if necessary or just single int value. – buran Sep 27 '21 at 12:30
  • [Check this out](https://stackoverflow.com/a/8230373/10217732) will help you to resolve your issue – Suyog Shimpi Sep 27 '21 at 12:32

1 Answers1

0

When you are creating your list of dicts your inner value of {4691} is actually a set not a dict.

https://realpython.com/python-sets/

Try this instead:

list_of_dicts = [{'f_note':'text','record_id': 4691},{'f_note':'sample','record_id': 4692}]

return jsonify(list_of_dicts)

See the error you encountered isolated

import json
test = {5565}

json.dumps(test)

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\p\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\p\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\p\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\p\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable

To keep the set functionaility you can cast it back to a list

remove_duplicates = [{**l[0], 'record_id': list(set([x['record_id'] for x in l]))} if len(l:=list(v)) > 1 else l[0] for _, v in groupby(sorted(list_of_dict, key=func), key=func)]
Pulsar
  • 21
  • 1
  • 4
  • i'm using the set to remove duplicates...so I'm getting value like this {4961}. – sruthi Sep 27 '21 at 12:37
  • Then cast it back to a list before you attempt to dump via JSON. This should solve your issue. remove_duplicates = [{**l[0], 'record_id': list(set([x['record_id'] for x in l]))} if len(l:=list(v)) > 1 else l[0] for _, v in groupby(sorted(list_of_dict, key=func), key=func)] – Pulsar Sep 27 '21 at 13:00