38

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);
2
  • 1
    OPENJSON is used in sqlserver (T-SQL), you tagged your question mysql. Wich are you using ? Commented Dec 2, 2016 at 11:19
  • i m using mysql 5.6 or ms sql server 2008 @JeanDoux Commented Dec 2, 2016 at 11:58

1 Answer 1

71

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json DEFAULT NULL, )' at line 2" this is the error i am encountering
MySQL 5.7 InnoDB or higher versions only supports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.