如何在Postgres查询中解析JSON数组

时间:2019-02-13 09:40:28

标签: postgresql

我需要从下表列中解析json数组。在下面的示例中,结果应为Q2问题的答案。

id      data
1   [{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]
2   [{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]

所以结果应该是这样

1 A2
2 A2

我尝试过   data::json->'answer' as answer,但似乎不适用于数组

2 个答案:

答案 0 :(得分:3)

您可以使用json_array_elements并使用WHERE子句过滤行

select id, j->>'answer' as answer FROM t 
cross join lateral json_array_elements(data::json) as j
WHERE j->>'questionId' = 'Q2'

Demo

答案 1 :(得分:1)

尝试the ># operator

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lc</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

输出:

create temporary table t (id serial primary key, data json);
insert into t (
  data
)
values (
  '[{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]'
);
insert into t (
  data
)
values (
  '[{"questionId":"Q1","answer":"A1"},{"questionId":"Q2","answer":"A2"}]'
);

-- The Q1 ist the 2nd element in the array and has index 1.
select id, data::json#>'{1,answer}' from t;