我有一个varchar专栏
{" l l": 2, " m m": 2, " xs xs": 2, " xxs xxs": 2, "s s": 0, "xl xl": 0}
如何过滤它以仅获得值大于0的键?预期输出为
{" l l": 2, " m m": 2, " xs xs": 2, " xxs xxs": 2}
xmd2e60i1#
你的数据看起来像json,所以你可以试着像一个人一样处理它--解析为json,把它变成map(varchar, integer)(或double),过滤,再回到字符串:
map(varchar, integer)
double
-- sample data with dataset(json_str) as ( values ('{" l l": 2, " m m": 2, " xs xs": 2, " xxs xxs": 2, "s s": 0, "xl xl": 0}') ) -- query select json_format(cast( map_filter(cast(json_parse(json_str) as map(varchar, integer)), (k, v) -> v > 0) as json)) from dataset;
输出:
_col0 ------------------------------------------------- {" l l":2," m m":2," xs xs":2," xxs xxs":2}
fdbelqdn2#
执行这项任务的一个备选办法是:
JSONB_EACH_TEXT
JSON_OBJECT
ARRAY_AGG
SELECT JSON_OBJECT(ARRAY_AGG(k), ARRAY_AGG(v)) FROM tab CROSS JOIN LATERAL JSONB_EACH_TEXT(tab.string) AS j(k,v) WHERE v::int > 0
输出:| json_对象|| - ------|| {" l l ":" 2 "," m m ":" 2 "," xs xs ":" 2 "," xxs xxs ":" 2 "}|检查here演示。
2条答案
按热度按时间xmd2e60i1#
你的数据看起来像json,所以你可以试着像一个人一样处理它--解析为json,把它变成
map(varchar, integer)
(或double
),过滤,再回到字符串:输出:
fdbelqdn2#
执行这项任务的一个备选办法是:
JSONB_EACH_TEXT
将json转换为表格JSON_OBJECT
+ARRAY_AGG
重新创建json输出:
| json_对象|
| - ------|
| {" l l ":" 2 "," m m ":" 2 "," xs xs ":" 2 "," xxs xxs ":" 2 "}|
检查here演示。