SQLite json_extract() 函数使用指南

来源:这里教程网 时间:2026-03-25 18:14:09 作者:

SQLite

json_extract()
函数在 JSON 文档提取路径表达式指定的数据并返回。

json_extract()
语法

这里是 SQLite

json_extract()
的语法:

json_extract(json, path, ...)

参数

json
必需的。一个 JSON 文档。
path
必需的。您应该至少指定一个路径表达式。

返回值

json_extract()
函数返回 JSON 文档中由路径表达式匹配的所有的值。如果路径表达式匹配了一个值,则返回该值,如果路径表达式匹配了多个值,则返回一个包含了所有值的数组。

如果存在以下的情况,

json_extract()
函数将返回
NULL

如果 JSON 文档中不存在指定的路径。如果任意一个参数为
NULL

如果参数

json
不是有效的 JSON 文档,SQLite 将会给出错误。您可以使用
json_valid()
验证 JSON 文档的有效性。

json_extract()
示例

这里列出了几个常见的

json_extract()
用法示例。

示例: 数组

下面的语句展示了如何从数组中提取一个元素:

SELECT json_extract('[1, 2, {"x": 3}]', '$[2]');

json_extract('[1, 2, {"x": 3}]', '$[2]')----------------------------------------{"x":3}

让我们再看一个带有多个路径参数的例子:

SELECT json_extract('[1, 2, {"x": 3}]', '$[2].x', '$[1]', '$[0]');

json_extract('[1, 2, {"x": 3}]', '$[2].x', '$[1]', '$[0]')----------------------------------------------------------[3,2,1]

示例: 对象

下面的语句展示了如何从对象中提取一个节点的值:

SELECT json_extract('{"x": 1, "y": [1, 2]}', '$.y');

json_extract('{"x": 1, "y": [1, 2]}', '$.y')--------------------------------------------[1,2]

让我们再看一个带有多个路径参数的例子:

SELECT json_extract('{"x": 1, "y": [1, 2]}', '$.x', '$.y');

json_extract('{"x": 1, "y": [1, 2]}', '$.x', '$.y')---------------------------------------------------[1,[1,2]]

其他示例

让我们再看几个实例:

SELECT    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$'),    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c'),    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2]'),    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2].f'),    json_extract('{"a":2,"c":[4,5],"f":7}','$.c','$.a'),    json_extract('{"a":2,"c":[4,5],"f":7}','$.c[#-1]'),    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x'),    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x', '$.a'),    json_extract('{"a":"xyz"}', '$.a'),    json_extract('{"a":null}', '$.a');

         json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$') = {"a":2,"c":[4,5,{"f":7}]}       json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c') = [4,5,{"f":7}]    json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2]') = {"f":7}  json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2].f') = 7    json_extract('{"a":2,"c":[4,5],"f":7}','$.c','$.a') = [[4,5],2]     json_extract('{"a":2,"c":[4,5],"f":7}','$.c[#-1]') = 5       json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x') =json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x', '$.a') = [null,2]                     json_extract('{"a":"xyz"}', '$.a') = xyz                      json_extract('{"a":null}', '$.a') =

相关推荐

热文推荐