删除JSON键中的前导和尾随空格

时间:2019-02-09 18:54:03

标签: mysql sql json mariadb

我正在尝试使用JSON_EXTRACT从我的MariaDB服务器获取JSON值。但是,有些JSON键具有很多空白,例如行尾,空格,制表符等。数据已经存在。因此,我无法给出正确的键名称,因为键包含空格。请注意,JSON值中也有空格,但是我们可以使用TRIM()函数从值中删除空格。但是我们该怎么做才能修剪键名?

例如:

CREATE TABLE test.product_json_table (
   id INT AUTO_INCREMENT NOT NULL,
   product VARCHAR(20) NOT NULL,
   description LONGTEXT ASCII,
  PRIMARY KEY (id),
    CHECK (JSON_VALID(description))
) ENGINE = InnoDB ROW_FORMAT = DEFAULT;



INSERT INTO test.product_json_table(product, description) 
VALUES( 'truck_space', '{"     \r\nwheels  ": 4, "seats": 3, "  fuel   ": "diesel", "  \r\n mileage     ": 8}');

以下查询无效:

SELECT id, product, description 
FROM test.product_json_table
WHERE JSON_EXTRACT(description, '$.wheels') > 2;

该查询不起作用,因为JSON键“ wheels”有空格。键“里程”也是如此。

我们如何解决此问题?预先感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用

REGEXP_REPLACE(query, '\\s|\\r|\\n','')

请参见

CREATE TABLE product_json_table (
   id INT AUTO_INCREMENT NOT NULL,
   product VARCHAR(20) NOT NULL,
   description LONGTEXT ASCII,
  PRIMARY KEY (id),
    CHECK (JSON_VALID(description))
) 
INSERT INTO product_json_table(product, description) 
VALUES( 'truck_space', REGEXP_REPLACE('{"     \r\nwheels  ": 4, "seats": 3, "  fuel   ": "diesel", "  \r\n mileage     ": 8}', '\\s|\\r|\\n',''));
select * from product_json_table
id | product     | description                                       
-: | :---------- | :-------------------------------------------------
 1 | truck_space | {"wheels":4,"seats":3,"fuel":"diesel","mileage":8}

db <>提琴here

答案 1 :(得分:1)

除了@BillKarwin建议在将空格输入数据库之前先修剪空格外,还可以更新数据库中的所有值以删除虚假空格:

UPDATE product_json_table
SET description = REGEXP_REPLACE(description, '\\s|\\r|\\n','');

然后您的原始查询将起作用:

SELECT id, product, description 
FROM product_json_table
WHERE JSON_EXTRACT(description, '$.wheels') > 2;

输出:

id  product         description
1   truck_space     {"wheels":4,"seats":3,"fuel":"diesel","mileage":8}

Demo on dbfiddle

更新

您也可以即时执行空白替换,尽管这比使用上面的UPDATE查询永久删除空白要低得多:

SELECT id, product, REGEXP_REPLACE(description, '\\s|\\r|\\n','') AS description 
FROM product_json_table
WHERE JSON_EXTRACT(REGEXP_REPLACE(description, '\\s|\\r|\\n',''), '$.wheels') > 2

输出:

id  product         description
1   truck_space     {"wheels":4,"seats":3,"fuel":"diesel","mileage":8}

Demo on dbfiddle