Unable to extract value from json array column in BigQUERY - arrays

I have a table column in BigQuery with JSON array format with a row like {"role":"SuperAdmin","_id":"abcd","userId":"efgh"}. This column schema in BigQuery is REPEATED mode. My goal is to extract the userId value for all the rows in that column.
I have tried using JSON functions like json_value and json_extract:
select json_value(column_name, '$.users.userId') as userId, from table_name
but get the following error :
No matching signature for function JSON_VALUE for argument types: ARRAY<STRING>, STRING. Supported signature: JSON_VALUE(STRING, [STRING]) at [2:3]
Please how do I go about it?

Because it is repeated you will need to unnest it first.
Given the following example:
with sample_data as (
select ['{"role":"SuperAdmin","_id":"abcd","userId":"efgh"}','{"role":"SuperAdmin","_id":"abcd","userId":"efgh"}','{"role":"SuperAdmin","_id":"abcd","userId":"efgh"}'] as users
)
select json_value(user, '$.userId') as userId
from sample_data , UNNEST(users) user
The return is:

Related

how to cast each row of type varchar to array?

So I have this problem. I have a table called Orders, where i have a column product_id, but it's of the type varchar, because there can be many of them e.g. '12,3,4,345'. They are all sepearted with ','
But my question is how can I cast in query each row of varchar to array?
I tried it with the string_to_array function, but it only casts one row. I need to cast all of the rows in the given table.
My code
SELECT o.product_id, string_to_array(
(select product_id
from orders), ',' ) as array
from orders o ;
I am working in IntellIJ, using JDBC driver on postresql database.
It would be nice if you attach sample data and expected output. So far, I understood your problem, that you want to "put" the contents of each line into an array.
SELECT product_id,
(string_to_array(product_id, ',')::int[]) as array
from orders;
Check out my dbfiddle and let me know if the result is different from what you want.

Snowflake Array to String issue

In Snowflake database, I'm trying to extract string from an array column.
The name of the column in the table is: mbus.
So, if you query the table:
select PRO.JSON_DATA:mbus
FROM SOURCE_TABLE1 PRO
the result will be:
[{"region":"EAME"},{"region":"LA"},[{"region":"NA"},[{"region":"NAP"},[{"region":"SAP"}]
I'm using ARRAY_TO_STRING function:
SELECT ARRAY_TO_STRING(PRO.JSON_DATA:mbus:region, ', ')
FROM SOURCE_TABLE1 PRO
, but the result is NULL.
The final result should be: EAME, LA, NA, NAP, SAP (Extracting from the column).
Could you help me on this one? I need to build a query to extract the properly strings from the array.
Using FLATTEN to transform json to rows and LISTAGG to combine back to single string:
SELECT LISTAGG(f.value:region::STRING, ',') AS col
FROM SOURCE_TABLE1 PRO
,LATERAL FLATTEN(input => PRO.JSON_DATE:mbus) f

convert one column to json

Using Azure SQLServer I'm trying to convert only one column to json format. The data is in a nvarchar field. Using For Json Auto will convert all fields and all rows. What I need is just to convert only one column.
By converting to json what I mean is to be clickable to see it's data a new window inside SSMS.
Let's say the table (Logs) has 2 columns: LogId and LogData. LogData is nvarchar(max) and contains json data.
What I need is to query the table and have a clickable logData column.
You can try like following to get only one column as JSON
select o.*,
(select YourColumnForJson
from YourTable i
where o.Identifer=i.Identifer for json auto) as JsonColumn
from YourTable o

How to extract a particular element from a json array in postgres?

I have a table parameter having 2 columns id(integer) and param_specs(text).
the actual param_specs column looks like above pic (to simplify it check below:-
)
param_specs
[
{"paramName":"param1",
"type":"string",
"defaultValue":"tomcat7",
"optional":false,
"deploymentParam":false},
{"paramName":"param123PreStopAction",
"type":"path",
"defaultValue":"HELLO",
"optional":false,
"deploymentParam":false}
]
So it is an array of json array and i want to fetch the defaultValue field of paramName param123PreStopAction i.e. HELLO.
****EDIT****
As can be seen in the image this is what my table called parameter looks like having two columns I want to get defaultValue of each row in parameter table where paramName LIKE (%PostStopAction) or (%PreStopAction) check the bold values in image(i.e. the paramName should have either PreStopAction or PostStopAction within the actual paramName value eg 'mytomcat7PostStopAction' and fetch its defaultValue i.e 'post-stop'.)
There can be some rows in the table where there wont be any json having preStop or PostStop paramName like row 3 in the image
can someone help me with the query?
As JGH suggested something as follows:-
SELECT "defaultValue"
FROM parameter a
CROSS JOIN LATERAL
json_to_recordset(a.param_spec::json) AS x("paramName" text,"defaultValue" text)
WHERE "paramName”LIKE “%PreStopAction' OR “paramName” LIKE “%PostStopAction”
One approach is to explode your array in fields and to query them. The trick is to consider only the fields of interest.
Select myOutputField
from json_to_recordset('[the array]') as (myQueryField text, myOutputField text)
where myQueryField = myCondition;
Or, bound to your example:
select "defaultValue" from json_to_recordset('
[
{"paramName":"param1",
"type":"string",
"defaultValue":"tomcat7",
"optional":false,
"deploymentParam":false},
{"paramName":"param123PreStopAction",
"type":"path",
"defaultValue":"HELLO",
"optional":false,
"deploymentParam":false}
]') as x("paramName" text,"defaultValue" text)
where "paramName" = 'param123PreStopAction';
** EDIT **
Your data is not saved in a json column but in a text column. You would have to convert it to json (ideally, the column itself... or at least its content). Also, the json_to_recordset works on single items, not on sets, so you would need to use a LATERAL JOIN to overcome this limitation, as nicely explained here.
SELECT myOutputField
FROM mytable a
CROSS JOIN LATERAL
json_to_recordset(a.jsonintextcolumn::json) as (myQueryField text, myOutputField text)
WHERE myQueryField = myCondition;
Or, bound to your example:
SELECT "defaultValue"
FROM public.testjsontxt a
CROSS JOIN LATERAL
json_to_recordset(a.param_specs::json) as x("paramName" text,"defaultValue" text)
WHERE "paramName" = 'param123PreStopAction';

Return rows where ID is in semicolon separated string from subquery MSSQL

I'm trying to query my sql database to return all the rows where the ID is contained in a separate tables column. The list of project IDs is kept in the Feedback table in the Project_ID Column with datatype varchar. I am trying to return the rows from the Projects table where the IDs are kept in the Project_ID column with datatype varchar.
I am doing this using the query
SELECT * FROM Projects WHERE Project_ID IN (
SELECT Project_ID FROM Feedback WHERE ID = 268 and Project_ID IS NOT NULL
)
When I run this query I am returned with the message:
Conversion failed when converting the varchar value '36;10;59' to data type int
This is yet another example of the importance of normalizing your data.
Keeping multiple data points in a single column is almost never the correct design, and by almost never I mean about 99.9999%.
If you can't normalize your database, you can use a workaround like this:
SELECT *
FROM Projects p
WHERE EXISTS (
SELECT Project_ID
FROM Feedback F WHERE ID = 268
AND Project_ID IS NOT NULL
AND ';'+ F.Project_ID +';' LIKE '%;'+ CAST(p.Project_ID as varchar) +';%'
)
You can't use the IN operator since it's expecting a list of values delimited by a comma, while you try to supply it with a single value that is delimited by a semicolon. Even if the values in Project_ID was delimited by a comma it would still not work.
The reason I've added the ; on each side of the Project_ID in both tables is that this way the LIKE operator will return true for any location it finds the Projects.Project_Id inside the Feedback.Project_Id. You must add the ; to the Projects.Project_Id to prevent the LIKE to return true when you are looking for a number that is a partial match to the numbers in the delimited string. Consider looking for 12 in a string containing 1;112;455 - without adding the delimiter to the search value (12 in this example) the LIKE operator would return true.

Resources