I'm writing function for a new postgreSQL db and i'm trying to loop over a nested structure.
Is that even possible with the new JSON functions? What i'm trying to do is here below:
DO
$BODY$
DECLARE
omgjson json := '[{ "type": false }, { "type": "photo" }, {"type": "comment" }]';
i record;
BEGIN
FOR i IN SELECT * FROM json_array_elements(omgjson)
LOOP
RAISE NOTICE 'output from space %', i;
END LOOP;
END;
$BODY$ language plpgsql
This returns a set of records (text!), that is not JSON! so i cannot query it like i->>'type'
, but that's exactly what i want to accomplish...
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
If you're using static JSON data and active data that's structured for SQL storage, Postgres is a good shout — its JSONB representation is efficient and allows for indexing.
PostgreSQL jsonbJSON data type stores the exact copy of input text in JSON. Jsonb stores the data as binary code. Basically, it stores the data in binary form which is not an ASCII/ UTF-8 string. Json preserves the original formatting like the whitespaces as well as the ordering of keys.
I was a little dumb, but the documentation on this json feature on postgresql website is actually minimal
to solve the problem all i did was
DO
$BODY$
DECLARE
omgjson json := '[{ "type": false }, { "type": "photo" }, {"type": "comment" }]';
i json;
BEGIN
FOR i IN SELECT * FROM json_array_elements(omgjson)
LOOP
RAISE NOTICE 'output from space %', i->>'type';
END LOOP;
END;
$BODY$ language plpgsql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With