简体   繁体   中英

Get value from json array object postgres

I have a query like this:

SELECT tags
FROM (
    SELECT trm.dado_id
        , json_agg(json_build_object('field',trm.nome, 'value',trm.valor)) AS tags
    FROM tb_dados trm
    JOIN tb_table1 t on trm.dado_id = t.id
    WHERE t.id = trm.dado_id
    GROUP BY trm.dado_id
    ) tabletags;

It returns me a lot of rows with json array field like this:

1  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-11"}]
2  |   [{"field" : "DATA CREATION", "value" : "21/09/1998"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-7"}]
3  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-7"}]
4  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-11"}]

...

Well, I want to query the row with has the SERIE NUMBER equals 00.000.000-11. There's a way of filter it?

You can filter the aggregation query with a HAVING clause. Also note that the subquery is not necessary here, and that the WHERE clause is redondant with the ON clause of the JOIN .

So:

SELECT json_agg(json_build_object('field', trm.nome, 'value', trm.valor)) AS tags
FROM tb_dados trm
JOIN tb_table1 t on trm.dado_id = t.id
GROUP BY trm.dado_id
HAVING bool_or(trm.nome = 'SERIE NUMBER' AND trm.valor = '00.000.000-11')

Side note: is there any reason why you are using json instead of jsonb ? The latter offers more functionalities, and should be generaly preferred. You can use jsonb_build_objet() and jsonb_agg() instead of the corresponding json_* functions.

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