MySQL JSON_SEARCH - 不使用双引号

时间:2017-12-12 17:31:45

标签: mysql json

我在user_details中有以下json数据:

"[{"value":"sachin","label":"What's your "first" name?"},{"value":"test@example.com","label":"What's your email?"},{"value":"+911234567890","label":"What's your "phone" number?"},{"value":"xyz","label":"What's your city?"},{"value":"abc","label":"What's your address?"}]"

为此,我尝试使用以下查询,但它给出了错误。只有当我的数据包含双引号(“)时才会发生错误。我怎样才能使这个工作?

SELECT CASE WHEN json_search(user_details, 'one', '%name%', null, '$[*].label')
IS NOT NULL THEN 'name'
WHEN json_search(user_details, 'one', '%email%', null, '$[*].label')
IS NOT NULL THEN 'email'
WHEN json_search(user_details, 'one', '%phone number%', null, '$[*].label') IS NOT NULL THEN 'phone'
ELSE 'id' END type,
CASE WHEN json_search(user_details, 'one', '%name%', null, '$[*].label')
IS NOT NULL THEN
json_unquote(json_extract(user_details, concat(json_unquote(replace(json_search(user_details, 'one', '%name%', null,
'$[*].label'),'.label', '')),'.value')))
WHEN json_search(user_details, 'one', '%email%', null, '$[*].label') IS NOT NULL THEN
json_unquote(json_extract(user_details, concat(json_unquote(replace(json_search(user_details, 'one', '%email%', null,
'$[*].label'),'.label', '')),'.value')))
WHEN json_search(user_details, 'one', '%phone number%', null, '$[*].label') IS NOT NULL THEN
json_unquote(json_extract(user_details,concat(json_unquote(replace(json_search(user_details, 'one', '%phone%', null,
'$[*].label'),'.label', '')),'.value')))ELSE user_id END value FROM json_user;

1 个答案:

答案 0 :(得分:0)

尝试:

mysql> SET @`user_details` := '[
    '>   {"value":"sachin","label":"What\'s your \\"first\\" name?"},
    '>   {"value":"test@example.com","label":"What\'s your email?"},
    '>   {"value":"+911234567890","label":"What\'s your \\"phone\\" number?"},
    '>   {"value":"xyz","label":"What\'s your city?"},
    '>   {"value":"abc","label":"What\'s your address?"}
    '> ]';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT JSON_VALID(@`user_details`);
+-----------------------------+
| JSON_VALID(@`user_details`) |
+-----------------------------+
|                           1 |
+-----------------------------+
1 row in set (0.00 sec)

mysql> SELECT
    -> JSON_UNQUOTE(
    ->   JSON_EXTRACT(
    ->     @`user_details`,
    ->     JSON_UNQUOTE(
    ->       REPLACE(
    ->         JSON_SEARCH(
    ->           @`user_details`,
    ->           'one',
    ->           '%phone%',
    ->           null,
    ->           '$[*].label'
    ->         ),
    ->         '.label',
    ->         '.value'
    ->       )
    ->     )
    ->   )
    -> ) `phone`;
+---------------+
| phone         |
+---------------+
| +911234567890 |
+---------------+
1 row in set (0.00 sec)