如何显示JSON数组的元素?

时间:2019-05-28 15:39:53

标签: sql json postgresql

我创建了一个带有json列的小表,我想像这样显示表中的所有名称:

 id_test |                                                                              test                                                                               
---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------
       1 | {"clients":{"nbr":"2","info":[{"nom":"med","genre":"male","age":"25"},{"nom":"aicha","genre":"female","age":"24"}]}}
       3 | {"clients":{"nbr":"3","info":[{"nom":"yns","genre":"male","age":"23"},{"nom":"oussama","genre":"male","age":"24"},{"nom":"sara","genre":"female","age":"27"}]}}
       2 | {"clients":{"nbr":"1","info":{"nom":"kenza","genre":"female","age":"26"}}}

所需的输出:

  name   
---------
 med
 aicha
 yns
 oussama
 sara
 kenza

我也想列出每种类型的性别数

所需的输出:

 genre  | count 
--------+-------
 female |     3
 male   |     3

1 个答案:

答案 0 :(得分:0)

使用JSON functions

第一个查询:

SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'nom' AS name
FROM my_table;

第二个查询:

SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'genre' AS genre,
    count(*)
FROM my_table
GROUP BY 1;