Search Json with null field value sql - mysql

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;

Related

How to convert tinyint back to boolean when reading from SQL?

`mysql> select * from movies;
+----------+-------+---------+
| movie_id | title | watched |
+----------+-------+---------+
| 1 | bo | 0 |
| 2 | NEW | 0 |
| 3 | NEW 2 | 0 |
+----------+-------+---------+
CREATE TABLE MOVIES (
movie_id INTEGER NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
watched BOOLEAN NOT NULL,
PRIMARY KEY (movie_id)
);
`
I am having to store the "watched" field as a tiny int instead of typical boolean, I am trying to find a way of converting it back to boolean when reading from table, so I dont have to loop through all responses and convert manually.
ie. {movie_id: 1, title: 'bo', watched: 0} ---> {movie_id: 1, title: 'bo', watched: false}
I have tried select cast but am unfamiliar with the syntax
MySQL saves Boolean as 0 and 1 as it handles all Boolean that way.
It is very practical, then you can add true or false from a comparison in a SUM without CASE WHEN or a FILTER
You need still to make a condition to give bak True or False, but they only text of course
SELECT
movie_id , title ,
CASE WHEN watched = 0 THEN 'False' ELSE 'True' END IF
This is similar to 'IF' in 'SELECT' statement - choose output value based on column values
Borrowing from the answer there,
SELECT movie_id, IF (watched > 0, true, false) as bwatched, ...
Note that this assumes your schema still includes "NOT NULL" for watched. Without that (or some extra code) NULL would become false.
The way "IF()" works is IF(expression , value / expression if true, v /e if false)

MySQL JSON object insert

I have the following JSON:
{
"params" : {
"A" : 200.5,
"B" : 70.2
}
}
And the following table:
CREATE TABLE `params` (
`param` varchar(255),
`value` float
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Is there a way to make mysql function with one insert query without using "while do" directly to insert all the parameters into table like this:
-------+-------
| param | value |
|-------+-------|
| A | 200.5|
| B | 70.2|
---------------
If you are running MySQL 8.0, you can use json_keys() to dynamically extract the keys from the json subobject as a json array, and then use json_table() to turn it to rows. You can then extract the values.
Consider:
insert into `params`
with t as (select '{"params": { "A": 200.5, "B": 70.2 } }' js)
select x.k, json_extract(js, concat('$.params.', x.k)) v
from
t
cross join json_table(
json_keys(js->"$.params"),
"$[*]" columns(k varchar(255) path "$")
) as x
Demo on DB Fiddle
Content of the table after running the query:
param | value
:---- | ----:
A | 200.5
B | 70.2
We can insert multiple rows with a single query using insert into. we need to construct this query using your JSON object
INSERT INTO params(param,value)
VALUES('A',200.5), ('B', 70.2);

Parsing JSon column value

I am trying to parse a json column from a table called Json_table which has 2 different types of elements,
keyfield | json_column | SomeotherField1 | SomeotherField2
----------------------------------------------------------------
keyfield1, | {"jField1":"Value1", ..."jField10":"Value10", "MapField":[{"Key": "key1", "Value":"Keyvalue1"}, {"Key": "key2", "Value":"Keyvalue2"}] | someothervalue | someothervalue
Using get_json_object function I can easily reach to jField1 to jField10 and MapField. But I dont know how i can parse MapField into further separate columns.
SELECT keyfield, get_json_object(json_column, '$.jField1') as jField1, get_json_object(json_column, '$.jField2') as jField2
FROM Json_table
I need to write query that would provide me results like this
Select Keyfield, jField1, jField2, .. , jField10, Key1, Key2 From Json_table
result as:
keyfield1 | Value1 | ... | Value10 | Keyvalue1 | Keyvalue2
I want to get all individual elements from within "Mapfield" part.
You can access MapField array by indexes, $.MapField[0].Value,
$.MapField[1].Value
with cte as (
select string('{"jField1":"Value1","jField10":"Value10", "MapField":[{"Key": "key1", "Value":"Keyvalue1"}, {"Key": "key2", "Value":"Keyvalue2"}]}')as jsn_col)
select get_json_object(jsn_col,'$.jField1')jField1,
get_json_object(jsn_col,'$.MapField[0].Value')key1,
get_json_object(jsn_col,'$.MapField[1].Value')key2 from cte;
+-------+---------+---------+
|jField1|key1 |key2 |
+-------+---------+---------+
|Value1 |Keyvalue1|Keyvalue2|
+-------+---------+---------+

SQL Server JSON_VALUE syntax

I created a SQL Server Table with 25 columns. One of my columns is actually JSON text, stored as nvarchar(max).
Now I need to able to query this JSON column and parse out the various attributes. I have tried applying JSON_VALUE to my column but am doing something wrong; my query runs but returns NULL for all the values.
The JSON itself looks like:
[
{
"lineName":"GHjr",
"pipeDiameter":"12",
"pipeLength":"52000",
"pressure":"15",
"volume":"107"
},
{
"lineName":"Ks3R",
"pipeDiameter":"9",
"pipeLength":"40000",
"pressure":"15",
"volume":"80"
}
]
The SQL I am using is:
select
DOC_ID, LINE_SPECS,
JSON_VALUE(LINE_SPECS, '$.lineName') as line_name,
JSON_VALUE(LINE_SPECS, '$.pipe_Diameter') as diameter
from dbo.MY_TEST_DOCS
where ISJSON(LINE_SPECS) > 0
and len(LINE_SPECS) > 3
However, my 2 "parsed" columns are returning all NULL. How do I parse the five attributes from this column?
Without the [] ISJSON is returning false
With [] ISJSON retuns true
Without the [] JSON_VALUE returns NULLs
With [] JSON_VALUE returns values
dbfddle.uk has sql server 2016 available....
create table test (LINE_SPECS nvarchar(max));
insert into test values (N'
{
"lineName":"GHjr",
"pipeDiameter":"12",
"pipeLength":"52000",
"pressure":"15",
"volume":"107"
},
{
"lineName":"Ks3R",
"pipeDiameter":"9",
"pipeLength":"40000",
"pressure":"15",
"volume":"80"
}
');
select *
from test
where ISJSON(LINE_SPECS) > 0
;
GO
| LINE_SPECS |
| :--------- |
select
JSON_VALUE(LINE_SPECS, '$.lineName') as line_name
, JSON_VALUE(LINE_SPECS, '$.pipeDiameter') as diameter
from test
;
GO
line_name | diameter
:-------- | :-------
GHjr | 12
dbfiddle here

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.