使用postgresql获取json中的元素

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

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

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

怎么做?这是json转储

8yoxcaq7

8yoxcaq71#

你可以这样做:

  1. SELECT
  2. (
  3. (
  4. (
  5. (
  6. (
  7. '{"pixel_rule":"{\"and\":[{\"event\":{\"eq\":\"Purchase\"}},{\"or\":[{\"content_ids\":{\"i_contains\":\"1000000007296871\"}}]}]}"}'::json->>'pixel_rule'
  8. )::json->>'and'
  9. )::json->1
  10. )::json->>'or'
  11. )::json->0->>'content_ids'
  12. )::json->>'i_contains';

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

js5cn81o

js5cn81o2#

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

  1. SELECT json_array_elements
  2. (
  3. json_array_elements(
  4. replace(trim((jsdata #>'{pixel_rule}')::text,'"'),'\','')::json -> 'and'
  5. ) -> 'or'
  6. )::json #>> '{content_ids,i_contains}' AS "Value"
  7. FROM tab

演示

gtlvzcf8

gtlvzcf83#

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

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

相关问题