json 过滤器具有特定值的键仅按下

j13ufse2  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(138)

我有一个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}
xmd2e60i

xmd2e60i1#

你的数据看起来像json,所以你可以试着像一个人一样处理它--解析为json,把它变成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}
fdbelqdn

fdbelqdn2#

执行这项任务的一个备选办法是:

  • 使用JSONB_EACH_TEXT将json转换为表格
  • 过滤掉等于0的值
  • 使用JSON_OBJECT + ARRAY_AGG重新创建json
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演示。

相关问题