mysql query to json convertor - mysql

How can I convert below query to json?
SELECT id ,name ,AddTime(created_at ,'04:30:00') as created_at2
I mean that I need something like this:
"select":[ "id","name" ],
"from":[
"table_name"
],
but I don't know how to use AddTime(created_at ,'04:30:00') as created_at2

Seems that you are looking for JSON_OBJECT() function in order to construct a JSON value such as
SELECT JSON_OBJECT(
'id', id,
'name', name,
'created_at2', AddTime(created_at ,'04:30:00')
) AS js
FROM t
Demo
Edit : perhaps you need to add JSON_ARRAY() function such as
SELECT JSON_OBJECT( 'select',
JSON_ARRAY( id, name, AddTime(created_at ,'04:30:00') )
) AS js
FROM t
Demo

Related

Syntax error: Unclosed string literal at [10:5]

SELECT type, key
FROM (
SELECT * FROM
js(
(SELECT json, type FROM arboreal-vision-339901.take_home.virtual_kitchen_ubereats_hours
),
-- Input columns.
json, type,
-- Output schema.
"[{name: 'key', type:'string'}, -- error here
{name: 'type', type:'string'}]",
-- The function.
"function(r, emit) {
x=JSON.parse(r.json)
Object.keys(x).forEach(function(entry) {
emit({key:entry, type:r.type,});
});
}"
)
)
LIMIT 10
can't understand why there's an error with "[{name: 'key', type:'string'}
could anyone please help me solve this. thanks!
For multi lines you need to use multi quotation marks i.e ””” or ’’’ at the beginning and end of the string. For more information you can refer to the google cloud documentation .
You can try this below query:
SELECT type, key
FROM (
SELECT * FROM
js(
(SELECT json, type FROM arboreal-vision-339901.take_home.virtual_kitchen_ubereats_hours
),
-- Input columns.
json, type,
-- Output schema.
"""[{name: 'key', type:'string'}, -- error here
{name: 'type', type:'string'}]""",
-- The function.
"""function(r, emit) {
x=JSON.parse(r.json)
Object.keys(x).forEach(function(entry) {
emit({key:entry, type:r.type,});
});
}"""
)
)
LIMIT 10

Is there any way to join multiple table and show result of some table as objects [duplicate]

I'd like to convert result table to JSON array in MySQL using preferably only plain MySQL commands. For example with query
SELECT name, phone FROM person;
| name | phone |
| Jack | 12345 |
| John | 23455 |
the expected JSON output would be
[
{
"name": "Jack",
"phone": 12345
},
{
"name": "John",
"phone": 23455
}
]
Is there way to do that in plain MySQL?
EDIT:
There are some answers how to do this with e.g. MySQL and PHP, but I couldn't find pure MySQL solution.
New solution:
Built using Your great comments, thanks!
SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person;
Old solution:
With help from #Schwern I managed to put up this query, which seems to work!
SELECT CONCAT(
'[',
GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
']'
)
FROM person;
You can use json_object to get rows as JSON objects.
SELECT json_object('name', name, 'phone', phone)
FROM person;
This won't put them in an array, or put commas between them. You'll have to do that in the code which is fetching them.
If you're stuck on MySQL 5.6 like me, try this:
SELECT
CONCAT(
'[',
GROUP_CONCAT(
CONCAT(
'{"name":"', name, '"',
',"phone":"', phone, '"}'
)
),
']'
) as json
FROM person
There are two "group by" functions for JSON called json_arrayagg, json_objectagg.
This problem can be solved with:
SELECT json_arrayagg(
json_merge(
json_object('name', name),
json_object('phone', phone)
)
) FROM person;
This requires MySQL 5.7+.
If you need a nested JSON Array Object, you can join JSON_OBJECT with json_arrayagg as below:
{
"nome": "Moon",
"resumo": "This is a resume.",
"dt_inicial": "2018-09-01",
"v.dt_final": null,
"data": [
{
"unidade": "unit_1",
"id_unidade": 9310
},
{
"unidade": "unit_2",
"id_unidade": 11290
},
{
"unidade": "unit_3",
"id_unidade": 13544
},
{
"unidade": "unit_4",
"id_unidade": 13608
}
]
}
You can also do it like this:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_lst_caso`(
IN `codigo` int,
IN `cod_base` int)
BEGIN
DECLARE json TEXT DEFAULT '';
SELECT JSON_OBJECT(
'nome', v.nome,
'dt_inicial', v.dt_inicial,
'v.dt_final', v.dt_final,
'resumo', v.resumo,
'data', ( select json_arrayagg(json_object(
'id_unidade',`tb_unidades`.`id_unidade`,
'unidade',`tb_unidades`.`unidade`))
from tb_caso_unidade
INNER JOIN tb_unidades ON tb_caso_unidade.cod_unidade = tb_unidades.id_unidade
WHERE tb_caso_unidade.cod_caso = codigo)
) INTO json
FROM v_caso AS v
WHERE v.codigo = codigo and v.cod_base = cod_base;
SELECT json;
END
For most situations, I use DataGreap, but for big tables, it is not work.
My GIST shell script

Data truncation: '' While Inserting or Updating Value

I am trying to Insert/update a string (JSON). While inserting/Updating the value I get data truncation error.
I have tried making a JSON type column and passing an JSON_OBJECT() type but that fails as well.
select '''[{"id":"1202","title":"Asian","notes":"","active":"1"}]''';
CREATE TABLE mktesttable (
id int NOT NULL,
s VARCHAR(34530) NOT NULL
);
INSERT INTO mktesttable
select 1, '''[{"id":"1202","title":"Asian","notes":"","active":"1"}]''';
select * from mktesttable;
// That Works
INSERT INTO mktesttable
SELECT
patient_data.id,
CONCAT(
'''[{"id":"', patient_data.race,
'","title":"', list_options.title,
'","notes":"', list_options.notes,
'","active":"', list_options.active,
'"}]'''
) as s
FROM
patient_data
INNER JOIN list_options
ON patient_data.race = list_options.id order by 1 desc
Yields same result (Id's and data varies) but doesn't work
Result Set
If you want to store JSON object, you should use the JSON datatype instead of strings. To create a JSON object, you can use JSON_OBJECT.
CREATE TABLE mktesttable (
id int NOT NULL,
s JSON NOT NULL
);
INSERT INTO mktesttable
SELECT
patient_data.id,
JSON_OBJECT(
'id', patient_data.race,
'title', list_options.title,
'notes', list_options.notes,
'active', list_options.active,
)
FROM
patient_data
INNER JOIN list_options
ON patient_data.race = list_options.id
ORDER BY patient_data.id desc
If you need a JSON array as shown in your sample data, then :
JSON_ARRAY(
JSON_OBJECT(
'id', patient_data.race,
'title', list_options.title,
'notes', list_options.notes,
'active', list_options.active,
)
)

How to convert result table to JSON array in MySQL

I'd like to convert result table to JSON array in MySQL using preferably only plain MySQL commands. For example with query
SELECT name, phone FROM person;
| name | phone |
| Jack | 12345 |
| John | 23455 |
the expected JSON output would be
[
{
"name": "Jack",
"phone": 12345
},
{
"name": "John",
"phone": 23455
}
]
Is there way to do that in plain MySQL?
EDIT:
There are some answers how to do this with e.g. MySQL and PHP, but I couldn't find pure MySQL solution.
New solution:
Built using Your great comments, thanks!
SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person;
Old solution:
With help from #Schwern I managed to put up this query, which seems to work!
SELECT CONCAT(
'[',
GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
']'
)
FROM person;
You can use json_object to get rows as JSON objects.
SELECT json_object('name', name, 'phone', phone)
FROM person;
This won't put them in an array, or put commas between them. You'll have to do that in the code which is fetching them.
If you're stuck on MySQL 5.6 like me, try this:
SELECT
CONCAT(
'[',
GROUP_CONCAT(
CONCAT(
'{"name":"', name, '"',
',"phone":"', phone, '"}'
)
),
']'
) as json
FROM person
There are two "group by" functions for JSON called json_arrayagg, json_objectagg.
This problem can be solved with:
SELECT json_arrayagg(
json_merge(
json_object('name', name),
json_object('phone', phone)
)
) FROM person;
This requires MySQL 5.7+.
If you need a nested JSON Array Object, you can join JSON_OBJECT with json_arrayagg as below:
{
"nome": "Moon",
"resumo": "This is a resume.",
"dt_inicial": "2018-09-01",
"v.dt_final": null,
"data": [
{
"unidade": "unit_1",
"id_unidade": 9310
},
{
"unidade": "unit_2",
"id_unidade": 11290
},
{
"unidade": "unit_3",
"id_unidade": 13544
},
{
"unidade": "unit_4",
"id_unidade": 13608
}
]
}
You can also do it like this:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_lst_caso`(
IN `codigo` int,
IN `cod_base` int)
BEGIN
DECLARE json TEXT DEFAULT '';
SELECT JSON_OBJECT(
'nome', v.nome,
'dt_inicial', v.dt_inicial,
'v.dt_final', v.dt_final,
'resumo', v.resumo,
'data', ( select json_arrayagg(json_object(
'id_unidade',`tb_unidades`.`id_unidade`,
'unidade',`tb_unidades`.`unidade`))
from tb_caso_unidade
INNER JOIN tb_unidades ON tb_caso_unidade.cod_unidade = tb_unidades.id_unidade
WHERE tb_caso_unidade.cod_caso = codigo)
) INTO json
FROM v_caso AS v
WHERE v.codigo = codigo and v.cod_base = cod_base;
SELECT json;
END
For most situations, I use DataGreap, but for big tables, it is not work.
My GIST shell script

Postgres 9.3 JSON Output multi-dimensional object

Given this query:-
SELECT id as id,
attributes->>'name' as file_name,
status
from workflow.events
where schema='customer'
and type='FILE_UPLOAD'
id,file_name, status
1,name,status
2,name2,status2
I want to output this structure:-
{
"1" :{"id" :"1", "file_name" : "name", "status" : "status1"},
"2" :{"id" :"2", "file_name" : "name2","status" : "status2"}
}
I can do it at the moment using string functions but this seems messy and inefficient. CAn it be done using the native postgresql json functions?
If you want to get two records with json, use row_to_json() function:
with cte as (
select
id as id,
attributes->>'name' as file_name,
status
from workflow.events
where schema='customer' and type='FILE_UPLOAD'
)
select row_to_json(c) from cte as c
output:
{"id":1,"file_name":"name","status":"status"}
{"id":2,"file_name":"name2","status":"status2"}
If you want to get json array:
with cte as (
select
id as id,
attributes->>'name' as file_name,
status
from workflow.events
where schema='customer' and type='FILE_UPLOAD'
)
select json_agg(c) from cte as c
output:
[{"id":1,"file_name":"name","status":"status"},
{"id":2,"file_name":"name2","status":"status2"}]
But for you desired output, I can only suggest string transformation:
with cte as (
select
id::text as id,
file_name,
status
from workflow.events
where schema='customer' and type='FILE_UPLOAD'
)
select ('{' || string_agg('"' || id || '":' || row_to_json(c), ',') || '}')::json from cte as c
sql fiddle demo