Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to loop over JSON Arrays in postgresql 9.3

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...

like image 876
Valerio Avatar asked Nov 28 '13 18:11

Valerio


People also ask

How do I query JSON data in PostgreSQL?

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.

Is Postgres good for JSON?

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.

What is the difference between JSON and Jsonb in PostgreSQL?

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.


1 Answers

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
like image 82
Valerio Avatar answered Oct 23 '22 16:10

Valerio