PostgreSQL script that should parse JSON field to a column gives NULL - json

Here is my statement:
SELECT
"raw_storage_basetransaction"."id",
"raw_storage_basetransaction"."r_v",
"raw_storage_basetransaction"."transaction_data",
"raw_storage_basetransaction"."entry_datetime",
"raw_storage_basetransaction"."owner_id",
("transaction_data" ->> 'SupplierDB') AS "v"
FROM
"raw_storage_basetransaction"
LIMIT 21
or
SELECT
"raw_storage_basetransaction"."id",
"raw_storage_basetransaction"."r_v",
"raw_storage_basetransaction"."transaction_data",
"raw_storage_basetransaction"."entry_datetime",
"raw_storage_basetransaction"."owner_id",
("raw_storage_basetransaction"."transaction_data" ->> 'SupplierDB') AS "v"
FROM
"raw_storage_basetransaction"
LIMIT 21
v is always NULL
What did I do wrong?
--UPD--
My fault. I wrote in jsonb field a unicode string instead of json-dict.

Related

Get nested objects values from JSON in Postgres

So here is my JSON column in my Postgres DB:
{
"objekt_art": {
"86": {
"code": "86",
"bezeichnung_de": "Kino",
"bezeichnung_fr": "Cinéma",
"bezeichnung_it": "Cinema",
"bezeichnung_en": null,
"kurz_bezeichnung_de": "Kino",
"relevant_fuer_berechnung_steuerquote": true
},
"27": {
"code": "27",
"bezeichnung_de": "Kiosk",
"bezeichnung_fr": "Kiosque",
"bezeichnung_it": "Chiosco",
"bezeichnung_en": null,
"kurz_bezeichnung_de": "Kiosk",
"relevant_fuer_berechnung_steuerquote": true
}
}
}
I need to be able to query the bezechnung_de for example where code = 86.
The number of code i can pass from another table.
How can i for example make a query with two columns. One with the number and the second with bezeichnung_de.
Like this:
Code Bez
86 Kino
Sample data structure and sample table for join data: dbfiddle
select
je.value -> 'code' as "Code",
je.value -> 'bezeichnung_de' as "Bez"
from
test t
cross join jsonb_each((data::jsonb ->> 'objekt_art')::jsonb) je
-- In table test_join I insert value 86 for join record
inner join test_join tj on je.key::int = tj.json_id
As you know the code, this is fairly easy:
select t.the_column -> 'objekt_art' -> '86' ->> 'code' as code,
t.the_column -> 'objekt_art' -> '86' ->> 'bezeichnung_de' as bez
from the_table t
where ...
The value '86' can be a parameter. The first expression to select the code isn't really needed though, as you could replace it with the constant value (=parameter) directly.
If the "outer" JSON key isn't the same value as the code value, you could use something like this:
select o.value ->> 'code' as code,
o.value ->> 'bezeichnung_de' as bez
from the_table t
cross join jsonb_each(t.the_column -> 'objekt_art') o(key, value)
where o.key = '86'
and ... other conditions ...
If you are using Postgres 13 or later, this can also be written as a JSON path expression:
select a.item ->> 'code' as code,
a.item ->> 'bezeichnung_de' as bez
from (
select jsonb_path_query_first(t.the_column, '$.objekt_art.* ? (#.code == "86")') as item
from the_table t
where ....
) a
All examples assume that the column is defined with the data jsonb which it should be. If it's not you need to cast it: the_column::jsonb

Search Json with null field value sql

Using SQL statement to query JSON field value that return "null" (String null) instead of NULL value
Sample JSON value in field name field
{
"a" : "a",
"b" : null
}
Query statement
SELECT field->>'$.b' FROM table_a;
Results
+---------------+-----------------------+
| field->>'$.b' | ISNULL(field->>'$.b') |
+---------------+-----------------------+
| null | 0 |
+---------------+-----------------------+
Is anyone have way to handle "null" (String null)?
You can use IFNULL() function, to handle the case when null values is present.
SELECT IFNULL(field->>'$.b', 'null') FROM table_a;

how sum column group by jsonḃ postgres

Hi I have a colum jsnoḃ with this values
proyectos:
nomḃre:character_varying
fecha:datetime
campos: jsonḃ
the value of campos is =
{"lista": [{"valor": "10", "nombre": "sueldo"}, {"valor": "20", "nombre": "sueldo"}, {"valor": "25", "nombre": "sueldo"}]}
I I run this query ḃut not working
SELECT jsonb_array_elements(campos->'lista')->'nombre' as content,
sum(((jsonb_array_elements(campos->'lista')->'valor'))::numeric) as cantidad
FROM proyectos GROUP BY jsonb_array_elements(campos->'lista')->'nombre
The console show me the message:
ERROR: cannot cast type jsonb to numeric
LINE 3: ...((jsonb_array_elements(campos->'lista')->'valor'))::numeric)...
^
********** Error **********
ERROR: cannot cast type jsonb to numeric
SQL state: 42846
Character: 137
Any idea ?
Use the function jsonb_array_elements() in a lateral join to get array elements as value, the ->> operator to get json objects as text and cast the valor objects to numeric.
select value->>'nombre' as nombre, sum((value->>'valor')::numeric)
from proyectos
cross join jsonb_array_elements(campos->'lista')
group by 1
nombre | sum
--------+-----
sueldo | 55
(1 row)

syntax error when trying to query json documents in postgresql

on my postgresql 9.6, I ran into an error with a table created like
create table jsonTest (id integer, data jsonb);
The table has the following data:
select * from jsonTest;
id | data
----+----------------------------------
1 | {"tags": ["AA", "BB", "CC"]}
2 | {"tags": ["BB", "DD"]}
2 | {"tags": ["CC"]}
4 | {"city": "austin", "tags": "EE"}
(4 rows)
But when I tried to select, got syntax error:
template1=# select * from jsonTest where data->>city = 'austin';
ERROR: column "city" does not exist
LINE 1: select * from jsonTest where data->>city = 'austin';
Any ideas? Thanks a lot!
The right operand of ->> operator for JSON object is text. Use the apostrophes for the key, because without them Postgres interprets the name as an identifier (a column name):
data->>'city'

query to Extract from Json in Postgres

I've a json object in my postgres db, which looks like as given below
{"Actor":[{"personName":"Shashi Kapoor","characterName":"Prem"},{"personName":"Sharmila Tagore","characterName":"Preeti"},{"personName":"Shatrughan Sinha","characterName":"Dr. Amar"]}
Edited (from editor: left the original because it is an invalid json, in my edit I fixed it)
{
"Actor":[
{
"personName":"Shashi Kapoor",
"characterName":"Prem"
},
{
"personName":"Sharmila Tagore",
"characterName":"Preeti"
},
{
"personName":"Shatrughan Sinha",
"characterName":"Dr. Amar"
}
]
}
the name of the column be xyz and I've a corresponding content_id.
I need to retrieve content_ids that have Actor & personName = Sharmila Tagore.
I tried many queries, among those these two where very possible query to get but still i didn't get.
SELECT content_id
FROM content_table
WHERE cast_and_crew #>> '{Actor,personName}' = '"C. R. Simha"'
.
SELECT cast_and_crew ->> 'content_id' AS content_id
FROM content_table
WHERE cast_and_crew ->> 'Actor' -> 'personName' = 'C. R. Simha'
You should use jsonb_array_elements() to search in a nested jsonb array:
select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor');
content_id | value
------------+-----------------------------------------------------------------
1 | {"personName": "Shashi Kapoor", "characterName": "Prem"}
1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
1 | {"personName": "Shatrughan Sinha", "characterName": "Dr. Amar"}
(3 rows)
Column value is of the type jsonb so you can use ->> operator for it:
select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor')
where value->>'personName' = 'Sharmila Tagore';
content_id | value
------------+--------------------------------------------------------------
1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
(1 row)
Note, if you are using json (not jsonb) use json_array_elements() of course.