简体   繁体   中英

Parse JSONarray in PostgreSQL Query using json_extract_path_text and json_array_elements

I have a PostgreSQL query like the following that works and returns foo as expected.

SELECT json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6') as foo

This does not work. It just returns null.

SELECT json_extract_path_text('{"f2":{"f3":1},"f4":[{"f5":99,"f6":"foo"},{"f5":99,"f6":"foo"}]}','f4', 'f6') as foo

I have tried about every combination of the functions I can find at PostgreSQL Function website. Thus my question is, how do I get to the foo in the json array?

so I did get this to work, but it seems like there has to be a better way:

SELECT 
json_extract_path_text(
    json_array_elements(
        cast(json_extract_path_text('{"f2":{"f3":1},"f4":[{"f5":99,"f6":"foo"},{"f5":99,"f6":"foo"}]}'::json,'f4') as json
            )
    ),'f6'
) as foo

Found another way to accomplish something similar that may be useful

someJsonColumn::json #>> '{someObj,0,SomeObj,0}' as myJsonField

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