【问题标题】:object of type set is not JSON serializableset 类型的对象不是 JSON 可序列化的
【发布时间】:2021-09-27 12:27:18
【问题描述】:

我正在尝试将以下列表传递给 ajax 响应,但我遇到了错误

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)]

我正在使用 set 删除重复的记录 ID

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

return jsonify(list_of_dicts )

set 类型的对象不是 JSON 可序列化的

请给我建议更好的选择。

【问题讨论】:

  • 为什么需要这个集合,例如{4691} 首先?建议我更好的选择 - 如有必要,使用不同的数据结构或仅使用单个 int 值。
  • Check this out 将帮助您解决问题

标签: python json dictionary


【解决方案1】:

当您创建字典列表时,您的 {4691} 的内部值实际上是一个集合而不是一个字典。

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

试试这个:

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

return jsonify(list_of_dicts)

查看您遇到的孤立错误

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

要保留设置的功能,您可以将其转换回列表

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)]

【讨论】:

  • 我正在使用该集合来删除重复项...所以我得到了这样的价值 {4961}。
  • 然后在尝试通过 JSON 转储之前将其转换回列表。这应该可以解决您的问题。 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)]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2021-03-11
  • 2021-07-04
  • 2021-12-10
  • 1970-01-01
  • 2021-09-27
  • 2019-09-04
相关资源
最近更新 更多