2

while searching for a way to insert array into single db columns, I found an article about inserting JSON string. However it wasn't explained how. I tried to search and find the way with no success.

I have the following table:

+---------+----------------+----+
|  Name   |      Type      |    |
+---------+----------------+----+
| id      | int            | AI |
| name    | String         |    |
| address | JSON(longtext) |    |
+---------+----------------+----+

What i want to do is insert a Json arry in the address column. like:

+----+-----------+------------------------------------------+
| id |   name    |                 address                  |
+----+-----------+------------------------------------------+
|  1 | User name | [{street: "street address", city: "Berlin"}] |
+----+-----------+------------------------------------------+

I thought about inserting the JSON as String but im not sure if this a good idea. Any suggestions?

GMB
  • 216,147
  • 25
  • 84
  • 135
Assad Rajab
  • 69
  • 1
  • 1
  • 11

5 Answers5

11

You can pass your data as a string, as long as it is valid JSON; MySQL will happily convert it for you under the hood.

insert into mytable (id, name, address)
values (
    1,
    'User name',
    '[{"street": "street address", "city": "Berlin"}]'
);

An alternative is to use JSON builder functions:

insert into mytable (id, name, address)
values (
    1,
    'User name',
    json_array(json_object('street', 'street address', 'city', 'Berlin'))
);
GMB
  • 216,147
  • 25
  • 84
  • 135
2

This works in my case. In summary use ARRAY[CAST('{"key": "val"}' as json)].

Example:

insert into <table_name> (id, name, address)
values ('1', 
        'User name', 
         array[cast('{"street": "street address", "city": "Berlin"}' as json)])
1
CREATE TABLE people (id INT, name VARCHAR(255), address JSON);

INSERT INTO people (id, name, address)
VALUES (1, 'User name', '[{"street": "street address", "city": "Berlin"}]');

SELECT *
FROM people;
id name address
1 User name [{"city": "Berlin", "street": "street address"}]

db<>fiddle here

Akina
  • 39,301
  • 5
  • 14
  • 25
1

Why converting to String if you already have a datatype JSON in MySQL

INSERT INTO <Table_Name> VALUES ('{street: "street address", city: "Berlin"}');

This insert statement will directly inserts your array. There is no need to convert.

See this stackoverflow answer

1

@GMB's alternative answer looks correct but I thought I would add another answer to show how I implemented this in a format that I prefer:

INSERT INTO <table name>  
SET field1 = '123',
    field2 = json_array(‘456’);

I like listing my field names next to their values so I don't have to mentally map the values to the variables.

Also, I didn't need the json_object since I was not entering a key:value pair - I was just entering a list of values.