Using LOAD DATA to import JSON data and specify date data type on import

流过昼夜 提交于 2019-12-25 02:23:15

问题


I'm importing JSON data in sql and would like like to convert human readable date data to yyyy-mm-dd format.

Here's the flow:

I'm using the following json file stored under /home/name/json_data/sample.json

{
    "price": null,
    "sale_list": [
        {
            "buyer": "SmackMe089",
            "date": "April 29th 2019 21:20:50",
            "id": "1234",
            "item_desc": ""
        }
}

Create the table in mysql:

CREATE TABLE example_table (
         id INT NOT NULL AUTO_INCREMENT,
         json_data JSON NOT NULL,
         PRIMARY KEY (id)
);

Loading the file into mysql:

LOAD DATA INFILE '/home/name/json_data/sample.json' INTO TABLE example_table (json_data);

When loading data into the table is possible convert the date data to yyyy-mm-dd? On querying I am able to assign data types to the columns, but not sure how to properly convert date data. Can this be done during querying or during import?

EX:

select test.* from example_table,
JSON_TABLE(json_data, '$.sale_list[*]' COLUMNS (
buyer VARCHAR(40) PATH '$.buyer',
date VARCHAR(40) PATH '$.date',
id VARCHAR(40) PATH '$.id',
item_desc VARCHAR(40) PATH '$.item_desc'
) ) test;

回答1:


I understand that you are using MySQL 8.0.4 or higher because you are using JSON_TABLE() function.

One option is to use STR_TO_DATE function:

SELECT
  `test`.`buyer`,
  STR_TO_DATE(`test`.`date`, '%M %D %Y') `date`,
  `test`.`id`,
  `test`.`item_desc`
FROM
  `example_table`,
  JSON_TABLE(
    `json_data`,
    '$.sale_list[*]' COLUMNS(
      `buyer` VARCHAR(40) PATH '$.buyer',
      `date` VARCHAR(40) PATH '$.date',
      `id` VARCHAR(40) PATH '$.id',
      `item_desc` VARCHAR(40) PATH '$.item_desc'
    )
  ) `test`;

See dbfiddle.

UPDATE

In LOAD DATA it is possible to convert the Date to the selected format, however, the sentence is somewhat more complicated and the file format to load must maintain the structure. In addition, in the new Date format, information such as Time will be lost:

LOAD DATA INFILE '/path/to/file/sample.json'
INTO TABLE `example_table` (@`json`)
SET `json_data` =
  JSON_REPLACE(
    @`json`,
    '$.sale_list[0].date',
    LEFT(
      STR_TO_DATE(
        JSON_UNQUOTE(
          JSON_EXTRACT(
            @`json`,
            '$.sale_list[0].date'
          )
        ),
      '%M %D %Y %H:%i:%s'),
    10)
  );


来源:https://stackoverflow.com/questions/55945889/using-load-data-to-import-json-data-and-specify-date-data-type-on-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!