简体   繁体   中英

MySQL 5.7 Escape forward slashes in JSON_EXTRACT key string

Quite simple problem that I can't find a solution for.

I have a simple JSON string:

{
  "A/B/C":"Random value"
}

It's stored in a MySQL database. I am trying to use JSON_EXTRACT to retrieve the data.

SELECT 
  JSON_EXTRACT(`json_data`, "$.A/B/C") AS 'A/B/C'
FROM `MyTable` 
WHERE 1

This of course throws an error due to the slashes. How can I query with the slashes without removing them from the original JSON?

You can get the results you want by quoting the key name in double quotes; this is required as it contains illegal path characters (see the manual ). This means you need to enclose the overall path in single quotes:

SET @json = '{
  "A/B/C":"Random value"
}'
;
SELECT JSON_EXTRACT(@json, '$."A/B/C"') AS 'A/B/C'

Output:

A/B/C
"Random value"

Demo on dbfiddle

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