跳转到内容
搜索文档

JSON 函数

最后更新 查看 MarkdownAgent 设置

Cloudflare Pipelines 提供两组 JSON 函数,第一组基于 PostgreSQL 的 SQL 函数和语法,第二组基于 JSONPath 标准。

SQL 函数

SQL 函数提供类似于 PostgreSQL 中的基本 JSON 解析函数。

json_contains

如果 JSON 字符串包含指定的键则返回 true

SELECT json_contains('{"a": 1, "b": 2, "c": 3}', 'a') FROM source;
true

也可通过 ? 运算符使用:

SELECT '{"a": 1, "b": 2, "c": 3}' ? 'a' FROM source;
true

json_get

通过指定路径(键)从 JSON 字符串检索值。以原生类型(string、int 等)返回值。

SELECT json_get('{"a": {"b": 2}}', 'a', 'b') FROM source;
2

也可通过 -> 运算符使用:

SELECT '{"a": {"b": 2}}'->'a'->'b' FROM source;
2

可使用 json_get 函数的各种变体以特定类型检索值,或使用 SQL 类型注解:

SELECT json_get('{"a": {"b": 2}}', 'a', 'b')::int FROM source;
2

json_get_str

通过指定路径从 JSON 字符串检索字符串值。如果值不存在或不是字符串则返回空字符串。

SELECT json_get_str('{"a": {"b": "hello"}}', 'a', 'b') FROM source;
"hello"

json_get_int

通过指定路径从 JSON 字符串检索整数值。如果值不存在或不是整数则返回 0

SELECT json_get_int('{"a": {"b": 42}}', 'a', 'b') FROM source;
42

json_get_float

通过指定路径从 JSON 字符串检索浮点值。如果值不存在或不是浮点数则返回 0.0

SELECT json_get_float('{"a": {"b": 3.14}}', 'a', 'b') FROM source;
3.14

json_get_bool

通过指定路径从 JSON 字符串检索布尔值。如果值不存在或不是布尔值则返回 false

SELECT json_get_bool('{"a": {"b": true}}', 'a', 'b') FROM source;
true

json_get_json

通过指定路径从 JSON 字符串检索嵌套 JSON 字符串。值以原始 JSON 形式返回。

SELECT json_get_json('{"a": {"b": {"c": 1}}}', 'a', 'b') FROM source;
'{"c": 1}'

json_as_text

通过指定路径从 JSON 字符串检索任何值,并以其字符串形式返回,无论原始类型如何。

SELECT json_as_text('{"a": {"b": 42}}', 'a', 'b') FROM source;
"42"

也可通过 ->> 运算符使用:

SELECT '{"a": {"b": 42}}'->>'a'->>'b' FROM source;
"42"

json_length

返回指定路径处 JSON 对象或数组的长度。如果路径不存在或不是对象/数组则返回 0

SELECT json_length('{"a": [1, 2, 3]}', 'a') FROM source;
3

JsonPath 函数

JSON 函数使用 JsonPath 提供基本的 JSON 解析函数,JsonPath 是用于查询 JSON 对象的演进标准。

extract_json

返回第一个参数中与第二个参数中的 JsonPath 匹配的 JSON 元素。返回值为 JSON 字符串数组。

SELECT extract_json('{"a": 1, "b": 2, "c": 3}', '$.a') FROM source;
['1']

extract_json_string

返回与 JsonPath 匹配的第一项的未转义字符串(如果它是字符串)。

SELECT extract_json_string('{"a": "a", "b": 2, "c": 3}', '$.a') FROM source;
'a'

这篇文档对您有帮助吗?