Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and insert a JSON object using MySQL queries?

I'm trying to create a JSON object and then read the values from it into MySQL table. But I'm facing errors and I'm new to both JSON and MySQL.

SET @j = '{"key1": "value1", "key2": "value2"}';
CREATE TABLE Person (name int,id int);
INSERT INTO Person (name,id) SELECT * FROM OPENJSON(@j) WITH (name int,id int);
like image 347
rj_23495 Avatar asked Dec 02 '16 11:12

rj_23495


People also ask

Can we insert JSON in MySQL?

The attributes field's column type has been declared to be JSON which is the native data type now available in MySQL. This allows you to use the various JSON related constructs in MySQL on the attributes field. This database design is not the best in terms of efficiency and accuracy.

How do I add a JSON object to a database?

Click the Add button and select Column. On the Column element, specify values for the Index and Value attributes. Click the Add button in the sub-menu and select Add Same. Repeat the last two steps to add additional columns and elements from the JSON file.

Can we query JSON in MySQL?

Starting with MySQL 8.0. 17, queries using JSON_CONTAINS() on InnoDB tables can be optimized using multi-valued indexes; see Multi-Valued Indexes, for more information. Returns 0 or 1 to indicate whether a JSON document contains data at a given path or paths.


1 Answers

On creating table set your field as JSON datatype.

CREATE TABLE `person` (
  `name` json DEFAULT NULL
);

And Insert JSON data into it,

INSERT INTO `person` (`name`)
VALUES ('["name1", "name2", "name3"]');

Or Insert JSON data by Key:Value

INSERT INTO person VALUES ('{"pid": 101, "name": "name1"}');
INSERT INTO person VALUES ('{"pid": 102, "name": "name2"}');

Select JSON data,

SELECT * FROM `person` WHERE JSON_CONTAINS(name, '["name1"]');

Note: Only supported by MySQL 5.7 (or higher) using InnoDB.

like image 123
saravanabawa Avatar answered Oct 05 '22 17:10

saravanabawa