简体   繁体   中英

JSON_EXTRACT as VALUES for INSERT INTO?

I expect the following MySQL code:

SET @json= '{"1":{"name":"Name","value":"James Bowery","id":1,"type":"name","first":"James","middle":"","last":"Bowery"},"2":{"name":"Birthdate","value":"06\/23\/2017","id":2,"type":"date-time","date":"06\/23\/2017","time":"","unix":1498176000},"3":{"name":"Gender","value":"Male","value_raw":"Male","id":3,"type":"radio"},"4":{"name":"Ethnicity","value":"European","value_raw":"European","id":4,"type":"radio"},"5":{"name":"Email","value":"jabowery@emailservice.com","id":5,"type":"text"}}';
SET @array = JSON_EXTRACT( @json, '$."1".first','$."1".last','$."5".value','$."2".value','$."3".value','$."4".value');
INSERT INTO user (firstname,lastname,birthdate,gender,ethnicity,email) VALUES (@array);

To insert a row into the user table populated by the named fields extracted from the JSON. However, the INSERT yields a syntax error. What is the proper syntax?

Perhaps try this. Note that I have changed the date format to yyyy-MM-dd. You will need to work on converting this programatically to fit to MySQL. Also, when I ran this, the array had email before birthdate, so I changed the sequence of insert.

 SET @json= '{"1":{"name":"Name","value":"James Bowery","id":1,"type":"name","first":"James","middle":"","last":"Bowery"},"2":{"name":"Birthdate","value":"06\/23\/2017","id":2,"type":"date-time","date":"2017-06-23","time":"","unix":1498176000},"3":{"name":"Gender","value":"Male","value_raw":"Male","id":3,"type":"radio"},"4":{"name":"Ethnicity","value":"European","value_raw":"European","id":4,"type":"radio"},"5":{"name":"Email","value":"jabowery@emailservice.com","id":5,"type":"text"}}';
SET @array = JSON_EXTRACT( @json, '$."1".first','$."1".last','$."5".value','$."2".value','$."3".value','$."4".value');
SET @queryString=   CONCAT( 'INSERT INTO user (firstname,lastname,email,birthdate,gender,ethnicity) VALUES (',REPLACE(REPLACE(@array, '[',''),']',''),')');
PREPARE stmt FROM @queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM