使用 common_schema 提取值不适用于嵌套 JSON

Extracting value using common_schema not working for nested JSON

我有一个名为 data 的数据库字段,类型为 MEDIUMTEXT,它以 JSON 格式存储值。我正在使用来自 common_schema.

extract_json_value 方法

当JSON不嵌套时,它工作正常。例如,当 applications_data table 的 data 字段为

{
  "key": "value"
}

这个查询工作正常:

SELECT data into @json from applications_data;
SELECT common_schema.extract_json_value(@json, 'key') as result;

并给出结果:key

但是,当数据字段是嵌套的 JSON 时,它会失败。例如,JSON 是:

{
  "key": {
    "overview": "sample"
  }
}

使用与上面相同的查询,结果为空,而不是 NULL:

记住:

extract_json_value

...

This function internally relies on json_to_xml(): it first converts the JSON data to XML, then uses ExtractValue to apply XPath.

...

ExtractValue(xml_frag, xpath_expr)

...

If no matching text node is found for the expression (including the implicit /text())—for whatever reason, as long as xpath_expr is valid, and xml_frag consists of elements which are properly nested and closed—an empty string is returned. No distinction is made between a match on an empty element and no match at all. This is by design.

If you need to determine whether no matching element was found in xml_frag or such an element was found but contained no child text nodes, you should test the result of an expression that uses the XPath count() function.

...

测试:

mysql> SET @`json` := '
    '> {
    '>   "key": {
    '>     "overview": "sample"
    '>   }
    '> }
    '> ';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT 
    ->   common_schema.extract_json_value(@`json`, 'key') AS result0,
    ->   common_schema.extract_json_value(@`json`, count('key')) AS result1,
    ->   common_schema.extract_json_value(@`json`, 'key/overview') AS result2,
    ->   common_schema.extract_json_value(@`json`, count('key/overview')) AS result3;
+---------+---------+---------+---------+
| result0 | result1 | result2 | result3 |
+---------+---------+---------+---------+
|         | 1       | sample  | 1       |
+---------+---------+---------+---------+
1 row in set (0.03 sec)