M
M
MarkusEfr2020-02-22 11:40:39
PostgreSQL
MarkusEfr, 2020-02-22 11:40:39

How to select data from JSON in Postgresql?

Greetings.
I have a front on which an object is formed in the form of json, then it is converted to a base64 string, through the back it gets into PostgreSQL (v. 11) where the string is converted back to json and you need to extract data from it by columns.
After being converted to the database, the json object looks like this
"{\"type\":[\"Shop\",\"Task\"],\"tag\":[\"code\",\"soft\", \"analytic\"]}"
and select all "type" and "tag" from it.

Tried doing it like this

The code

CREATE OR REPLACE FUNCTION filtering(
  filter64base text)
    RETURNS 
  TABLE(type text, tag text) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE
filterString character varying(200) = (SELECT CONVERT_FROM(DECODE($1, 'BASE64'), 'UTF-8'));  
isTypes boolean;
isTags boolean;
BEGIN
DROP TABLE IF EXISTS FilterJsonData;
  CREATE 
  TEMP TABLE 
  FilterJsonData(stringObj json);

  INSERT INTO FilterJsonData(stringObj)
  VALUES
  ((SELECT to_json(filterString)));
  
  RETURN QUERY
  SELECT 
     stringObj::json->>'type',
     stringObj::json->>'tag'
    FROM FilterJsonData;
END;
$BODY$;


But this is how null is selected for both fields, although the data is available ..
Please help - how to choose types and tags?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MarkusEfr, 2020-03-05
@MarkusEfr

the problem was due to the fact that extra characters "\" and "appeared during the conversion, so json was read incorrectly

M
Melkij, 2020-02-22
@melkij

select * from json_each('{"a":"foo", "b":"bar"}')
https://www.postgresql.org/docs/current/functions-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question