使用postgresql获取json中的元素

cedebl8k  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(391)

我有这个json,我想在sql中得到这部分:“100000007296871”

{"pixel_rule":"{\"and\":[{\"event\":{\"eq\":\"Purchase\"}},{\"or\":[{\"content_ids\":{\"i_contains\":\"1000000007296871\"}}]}]}"}

怎么做?这是json转储

8yoxcaq7

8yoxcaq71#

你可以这样做:

SELECT
(
    (
        (
            (
                (
                    '{"pixel_rule":"{\"and\":[{\"event\":{\"eq\":\"Purchase\"}},{\"or\":[{\"content_ids\":{\"i_contains\":\"1000000007296871\"}}]}]}"}'::json->>'pixel_rule'
                )::json->>'and'
            )::json->1
        )::json->>'or'
    )::json->0->>'content_ids'
)::json->>'i_contains';

但是您的输入有一点非常有趣,因为它包含多次嵌套在json中的json。

js5cn81o

js5cn81o2#

一种方法是通过修剪对象的 Package 引号来平滑对象 pixel_rule 的值,然后去掉多余的反斜杠,并应用 json_array_elements 为了使用 #>> 具有相关路径以提取所需值的运算符:

SELECT json_array_elements
       (
        json_array_elements(
           replace(trim((jsdata #>'{pixel_rule}')::text,'"'),'\','')::json -> 'and'
        ) -> 'or'
       )::json #>> '{content_ids,i_contains}' AS "Value"
  FROM tab

演示

gtlvzcf8

gtlvzcf83#

我的选择是使用 regex “\d+”如果其他部分不是数字

select substring('string' from '\d+')

相关问题