我有一个像下面这样的元组列表 -[(float.inf, 1.0), (270, 0.9002), (0, 0.0)]
我正在寻找一个简单的序列化器/反序列化器,它可以帮助我将此元组存储在 PostgreSQL 的 jsonb 字段中。
我尝试使用 JSONEncoder().encode(a_math_function)
但没有帮助。
我在尝试将上述列表存储在 jsonb 字段中时遇到以下错误 -
django.db.utils.DataError: invalid input syntax for type json
LINE 1: ...", "a_math_function", "last_updated") VALUES (1, '[[Infinit...
DETAIL: Token "Infinity" is invalid.
注意:字段 a_math_function 是 JSONField() 类型
最佳答案
t=# select 'Infinity'::float;
float8
----------
Infinity
(1 row)
因为
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-FLOAT
In addition to ordinary numeric values, the floating-point types have several special values:
Infinity
-Infinity
NaN
然而,json 没有这样的可能值(除非它的字符串)
https://www.json.org/
value string number object array true false null
因此:
t=# select '{"k":Infinity}'::json;
ERROR: invalid input syntax for type json
LINE 1: select '{"k":Infinity}'::json;
^
DETAIL: Token "Infinity" is invalid.
CONTEXT: JSON data, line 1: {"k":Infinity...
Time: 19.059 ms
所以这不是 jango 或 postgres 限制——只是
Infinity
是无效标记,而 'Infinity'
是有效字符串。所以t=# select '{"k":"Infinity"}'::json;
json
------------------
{"k":"Infinity"}
(1 row)
有效......但这里的
Infinity
是“只是一个字”。当然,您可以将其保存为字符串,而不是数值,并检查每个字符串是否不等于 "Infinity"
,如果是 - 启动您的程序逻辑以将其视为真正的无限...但简而言之 - 您不能这样做,因为 json 规范不支持它......就像你不能存储一样,让我们说红色 #ff0000
作为 json 中的颜色 - 仅作为字符串,由你的引擎捕获和处理......更新:
postgres 会将 float 转换为
to_json
上的文本本身:t=# select to_json(sub) from (select 'Infinity'::float) sub;
to_json
-----------------------
{"float8":"Infinity"}
(1 row)
更新
https://www.postgresql.org/docs/current/static/datatype-json.html
When converting textual JSON input into jsonb, the primitive types described by RFC 7159 are effectively mapped onto native PostgreSQL types
...
number numeric NaN and infinity values are disallowed
关于django - 通过 django 在 postgres json 中存储无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48356938/