1

I need to insert the below JSON into a MySQL table as below.

{
  "RelationshipType" : [ 
    {
        "ID" : 1,
        "FromID" : 70,
        "ToID" : 12
    },
    {
        "ID" : 3,
        "FromID" : 80,
        "ToID" : 1
    }
  ]
}

Expected output

ID    |    FromID    |    ToID    |
1     |     70       |     12     |
3     |     80       |     1      |

I used the below code to do the same in SQL Server. Is there any matching function to OPENJSON in MySQL.

DECLARE @Relationship AS TABLE(FromID INT,ToID INT,ID INT)
INSERT INTO @Relationship (FromID,ToID,ID)
SELECT FromID, ToID, ID
FROM OPENJSON(@RelationshipType)
WITH (FromID INT, ToID INT, ID INT)
4
  • 1
    Look at inserting the JSON document into a JSON data type column and then using JSON_TABLE to temporarily change the unstructured JSON data into a structured table. Commented Aug 2, 2019 at 11:38
  • What version of MySQL will be used?. Commented Aug 2, 2019 at 18:05
  • Thanks, @DaveStokes, Could you please provide any reference link or answer if you have Commented Aug 3, 2019 at 18:10
  • For an intro to JSON_TABLE() see elephantdolphin.blogspot.com/2019/05/… Commented Aug 5, 2019 at 13:48

1 Answer 1

1

Below is an example using JSON_TABLE(). I tested this on MySQL 8.0.16 in my sandbox environment.

mysql> create table relationship(id int primary key, fromid int, toid int);

mysql> insert into relationship select * from json_table(
'{ "RelationshipType" : [ { "ID" : 1, "FromID" : 70, "ToID" : 12 }, { "ID" : 3, "FromID" : 80, "ToID" : 1 } ] }',
'$.RelationshipType[*]' columns (
  id int path '$.ID',
  fromid int path '$.FromID',
  toid int path '$.ToID'
)) as j
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from relationship;
+----+--------+------+
| id | fromid | toid |
+----+--------+------+
|  1 |     70 |   12 |
|  3 |     80 |    1 |
+----+--------+------+

The JSON_TABLE() function requires MySQL 8.0.4 or later. It isn't implemented in earlier versions of MySQL.

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

2 Comments

Do you have any solution for this stackoverflow.com/questions/57475029/…
That's a duplicate question, another user gave you a link, and I voted to close your question as a duplicate.

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.