How to convert Result set into Json in MYSQL - mysql

select id,name,age from person where id=1;
This query gives result like below
id | name | age
1 |manoj | 20
I want a JSON like below
"{"id":1,"name":"manoj","age":5}"
I want a dynamic way.When I try another query from another table ,that result as like previous JSON
I want to generate JSON from a table and store into a column in MYSQL, I don't want to use php or other server side language for generate this JSON.
How can I get JSON in MYSQL ?

Use the JSON_OBJECT() function:
SELECT JSON_OBJECT('id', id, 'name', name, 'age', age)
FROM person
WHERE id = 1;
This requires at least MySQL 5.7 or MariaDB 10.2.3, that's when all the JSON-related functions were added.
If you don't want to hard-code the column names into the query, you'll need to write a stored procedure that creates dynamic SQL, using INFORMATION_SCHEMA.COLUMNS to get all the column names.

Look into JSON data type and JSON functions. If column is of JSON data type and insert string is in JSON format it's easy to insert and retrieve too.
MySQL JSON data type
JSON functions

Related

How do I return a JSON updated document in Oracle?

From the docs I see an example:
SELECT json_mergepatch(po_document, '{"Special Instructions":null}'
RETURNING CLOB PRETTY)
FROM j_purchaseorder;
But When I try this code in SQL Developer I get a squiggly line under CLOB and an error when I run the query?
It works in Oracle 18c:
SELECT json_mergepatch(
po_document,
'{"Special Instructions":null}'
RETURNING CLOB PRETTY
) AS updated_po_document
FROM j_purchaseorder;
Which for the test data:
CREATE TABLE j_purchaseorder( po_document CLOB CHECK ( po_document IS JSON ) );
INSERT INTO j_purchaseorder ( po_document )
VALUES ( '{"existing":"value", "Special Instructions": 42}' );
Outputs:
| UPDATED_PO_DOCUMENT |
| :------------------------------- |
| {<br> "existing" : "value"<br>} |
Removing the Special Instructions attribute as per the documentation you linked to:
When merging object members that have the same field:
If the patch field value is null then the field is dropped from the source — it is not included in the result.
Otherwise, the field is kept in the result, but its value is the result of merging the source field value with the patch field value. That is, the merging operation in this case is recursive — it dives down into fields whose values are themselves objects.
db<>fiddle here

Error retrieving JSON field in a PostgreSQL column Select

I'm trying to perform a SELECT at a PostgreSQL table with a JSON column. The problem is that that column is not a real JSON.
When I export to CSV the result is the following:
"{""access"":""1.SQnGhZKY4cemiRU+Svteoj2ZPQJ74uqXoWmGg0BmVf8ho3D2c7g1xYogcwz"",""objectId"":""58e3a109b48a6"",""deviceId"":""58e65028b4567"",""deviceBusinessUnits"":[],""crmId"":""443-f01246e5"",""crmBusinesUnits"":[],""crm"":{""gender"":""m"",""birthDate"":"""",""age"":null,""customFields"":{""displayName"":""te4"",""givenName"":""test"",""familyName"":""test"",""email"":""tes#yopil.net"",""mobileNumber"":""68"",""mobileNumberCountryCode"":""34"",""residencyCountry"":""LUX"",""mailingStreetName1"":null,""mailingStreetName2"":null,""mailingSubAdministrativeArea"":null,""mailingMunicipality"":null,""mailingPostalCode"":""208"",""mailingAdministrativeArea"":null,""mailingCountry"":null,""shippingStreetName1"":null,""shippingStreetName2"":null,""shippingSubAdministrativeArea"":null,""shippingMunicipality"":null,""shippingPostalCode"":null,""shippingAdministrativeArea"":null,""shippingCountry"":null},""tags"":[],""businessUnits"":[],""crmProvider"":{""type"":""cid"",""sessionToken"":""7drmcvu""}}}"
My column is named "user" and my query is:
select
mytable.user ->> 'accessToken' as userRaw
from mytable;
But I get:
How could I get the JSON values from this column?

Using json as column name in cassandra table does not work after cassandra upgrade

Recently there was a driver upgrade for Cassandra from 2.0.4 to 3.1.0 in my project. I found that the insert statement does not work on the tables that has 'json' as column name. The same insert statement used to work on previous cassandra version.
Sample insert statement:
insert into table_name (name, id, json) values ("AAA", "123", '{"display-order":"1","product-id":"QWERTY"}');
When I tried the query in Datastax DevCenter, I am getting the error as "no viable alternative at input 'json'"
Does that mean that we have to change the insert statements?
Please help!
Edit:
I made a mistake in the example query, json type is not the issue. When I enabled debug I found that the issue is with timestamp column.
I did not mention that in my example as I thought json could be the reason.
This is because of the recent driver update to 3.1.0, as the same query does not work now.
When I tried to fix it, I could not find the timestamp converter function (toTimestamp) or the dateOf() function in 3.1.0 version.
I see only now() but it returns only of type timeuuid.
Is there any other way I can convert the current date to timestamp?
It's not because of json field, your insert format is not correct
Use string as enclosed with single quote :
cassandra#cqlsh:test> insert into test_json (name, id, json) values ('AAA', '123', '{"display-order":"1","product-id":"QWERTY"}');
cassandra#cqlsh:test> SELECT * FROM test_json ;
id | json | name
-----+---------------------------------------------+------
123 | {"display-order":"1","product-id":"QWERTY"} | AAA
Or Double dollar signs to enclose a string with quotes, backslashes, or other characters that would normally need to be escaped
cassandra#cqlsh:test> insert into test_json (name, id, json) values ('AAA', '123', $${"display-order":"1","product-id":"QWERTY"}$$);
cassandra#cqlsh:test> SELECT * FROM test_json ;
id | json | name
-----+---------------------------------------------+------
123 | {"display-order":"1","product-id":"QWERTY"} | AAA
By the way, if you want to insert current timestamp use dateof(now()) or if you use java use new Date()

Save data from a field that contains json into another field of the database

I have a MySQL database which has two fields. The first field is named postValues and the other one is named username. The username is null to all records of my database.
Inside the field postValues there is a JSON string.
In this JSON string there might be a key username.
{
otherfields,
"username": "George",
otherfields
}
There is also a chance that the username does not exist.
I need with an SQL query to check every record of the database if the key username exists inside the JSON string and if it exists save it to the same record at field username. Notice that the otherfields are not the same to every record and also the key username might not be in the same position to take the substr from the JSON string. I guess I need a regexp here.
Can anyone guide me.
You can use mysql to determine if the value exists, after all JSON data is just a string. So as long as you know the structure of the string you can get it.
Here's an example using REGEXP but you could also use LIKE.
SELECT (CASE WHEN `postValues` REGEXP '"username":"([a-zA-Z0-9]+)"' THEN 'YES' ELSE 'NO' END) AS `hasUserName` FROM `table`;
You could also use mysql to do the update to add the name to the other column. This gets really complicated really quickly but it works. Tested with {"bla":123,"username":"Goerge","more":"abc"}
UPDATE `table` SET `username`=(
CASE WHEN `postValues` REGEXP '"username":"([a-zA-Z0-9]+)"' THEN
(SUBSTRING_INDEX(REPLACE(REPLACE(`postValues`,SUBSTRING_INDEX(`postValues`,'"username":"',1),''), '"username":"', ''), '"', 1))
ELSE NULL END
);

how to parse json using json_populate_recordset in postgres

I have a json stored as text in one of my database row. the json data is as following
[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]
to parse this i want to use postgresql method
json_populate_recordset()
when I post a command like
select json_populate_recordset(null::json,'[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]') from anoop;
it gives me following error
first argument of json_populate_recordset must be a row type
note : in the from clause "anoop" is the table name.
can anyone suggest me how to use the json_populate_recordset method to extract data from this json string.
I got method's reference from
http://www.postgresql.org/docs/9.3/static/functions-json.html
The first argument passed to pgsql function json_populate_recordsetshould be a row type. If you want to use the json array to populate the existing table anoop you can simply pass the table anoop as the row type like this:
insert into anoop
select * from json_populate_recordset(null::anoop,
'[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},
{"id":67273,"name":"16167.txt"},
{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]');
Here the null is the default value to insert into table columns not set in the json passed.
If you don't have an existing table, you need to create a row type to hold your json data (ie. column
names and their types) and pass it as the first parameter, like this anoop_type:
create TYPE anoop_type AS (id int, name varchar(100));
select * from json_populate_recordset(null :: anoop_type,
'[...]') --same as above
no need to create a new type for that.
select * from json_populate_recordset(null::record,'[{"id_item":1,"id_menu":"34"},{"id_item":2,"id_menu":"35"}]')
AS
(
id_item int
, id_menu int
)