简体   繁体   中英

Get an element in Json using PostgreSQL

I have this JSON and I want to get this part: '1000000007296871' in SQL

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

How to do that? this is JSON Dump

Well, you can do this like so:

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';

But something is really funny about your input, since it contains json nested in json multiple times.

One option would be smoothing the object by trimming the wrapper quotes of the pixel_rule 's value, and then getting rid of redundant backslashes, and applying json_array_elements function consecutively in order to use #>> operator with the related path to extract the desired value:

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

Demo

my option is using regex '\d+' if other part is not digit

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM