JSON_EXTRACT_PATH_TEXT 函数 - AWS Clean Rooms

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

JSON_EXTRACT_PATH_TEXT 函数

JSON_EXTRACT_PATH_TEXT 函数返回 JSON 字符串中的一系列路径元素引用的 key:value 对的值。JSON 路径最深可嵌套至 5 层。路径元素区分大小写。如果 JSON 字符串中不存在路径元素,JSON_EXTRACT_PATH_TEXT 将返回空字符串。如果 null_if_invalid 参数设置为 true 并且 JSON 字符串无效,函数将返回 NULL 而不是返回错误。

有关其他 JSON 函数的信息,请参阅 JSON 函数

语法

json_extract_path_text('json_string', 'path_elem' [,'path_elem'[, …] ] [, null_if_invalid ] )

参数

json_string

格式正确的 JSON 字符串。

path_elem

JSON 字符串中的路径元素。需要一个路径元素。可指定额外的路径元素,最深五层。

null_if_invalid

一个布尔值,指定在输入 JSON 字符串无效时是否返回 NULL 而不返回错误。要在 JSON 无效时返回 NULL,请指定 true (t)。要在 JSON 无效时返回错误,请指定 false (f)。默认为 false

在 JSON 字符串中,AWS Clean Rooms 将 \n 识别为换行符,将 \t 识别为制表符。要加载反斜杠,请使用反斜杠 ( \\ ) 对其进行转义。

返回类型

表示路径元素引用的 JSON 值的 VARCHAR 字符串。

示例

以下示例返回路径 'f4', 'f6' 的值。

select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}}','f4', 'f6'); json_extract_path_text ---------------------- star

在以下示例中,因为 JSON 无效,所以返回错误。

select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}','f4', 'f6'); An error occurred when executing the SQL command: select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}','f4', 'f6')

以下示例将 null_if_invalid 设置为 true,因此语句在 JSON 无效时返回 NULL 而不是返回错误。

select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}','f4', 'f6',true); json_extract_path_text ------------------------------- NULL

以下示例返回路径 'farm', 'barn', 'color' 的值,其中检索到的值位于第三级。为更便于阅读,此示例使用 JSON lint 工具进行格式化。

select json_extract_path_text('{ "farm": { "barn": { "color": "red", "feed stocked": true } } }', 'farm', 'barn', 'color'); json_extract_path_text ---------------------- red

以下示例返回 NULL,因为 'color' 元素缺失。此示例使用 JSON lint 工具进行格式化。

select json_extract_path_text('{ "farm": { "barn": {} } }', 'farm', 'barn', 'color'); json_extract_path_text ---------------------- NULL

如果 JSON 有效,则尝试提取缺失的元素将返回 NULL。

以下示例返回路径 'house', 'appliances', 'washing machine', 'brand' 的值。

select json_extract_path_text('{ "house": { "address": { "street": "123 Any St.", "city": "Any Town", "state": "FL", "zip": "32830" }, "bathroom": { "color": "green", "shower": true }, "appliances": { "washing machine": { "brand": "Any Brand", "color": "beige" }, "dryer": { "brand": "Any Brand", "color": "white" } } } }', 'house', 'appliances', 'washing machine', 'brand'); json_extract_path_text ---------------------- Any Brand