Oracle 从带有连字符键的 JSON 列中选择

And*_*ose 2 oracle json hyphenation

假设我将以下内容存储在 Oracle 数据库的 JSON 列中:

{
    "key-with-hyphens": "value"
}
Run Code Online (Sandbox Code Playgroud)

json_column假设此列在名为 的表中被调用,那么我尝试像这样my_table选择键的值:"key-with-hyphens"

select json_column.key-with-hyphens from my_table;
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

{
    "key-with-hyphens": "value"
}
Run Code Online (Sandbox Code Playgroud)

从 Oracle 中的 JSON 列中选择连字符键的值时,是否需要使用某种特殊语法?

And*_*ose 6

事实证明,有几种方法可以做到这一点。

方法一:

按照我尝试的原始方式进行操作,此选择存在几个问题:

select json_column.key-with-hyphens from my_table;
Run Code Online (Sandbox Code Playgroud)

首先,除非您为表添加别名,否则 JSON 列中的键选择将不起作用,如下所示:

select mt.json_column.key-with-hyphens from my_table mt;
Run Code Online (Sandbox Code Playgroud)

但是,这仍然无法解决连字符键的问题。要在此语法中允许使用连字符键,您需要将键的名称括在引号中:

select mt.json_column."key-with-hyphens" from my_table mt;
Run Code Online (Sandbox Code Playgroud)

上述查询将按预期工作。

方法二:

另一种无需为表添加别名的方法是使用json_valueselect 子句中的函数。您将 JSON 列作为第一个参数传递,并将要选择的键的完整路径作为第二个参数传递,用作$存储在列中的 JSON 对象的根上下文。以下查询也应该按预期工作:

select json_value(json_column, '$."key-with-hyphens"') from my_table;
Run Code Online (Sandbox Code Playgroud)