Função JSON_EXTRACT_PATH_TEXT
nota
O JSON_PARSE e suas funções associadas analisam os valores JSON como SUPER, que o Amazon Redshift analisa com maior eficiência do que o VARCHAR.
Em vez de usar JSON_EXTRACT_PATH_TEXT, recomendamos que você analise suas strings JSON usando o Função JSON_PARSE para ter um valor SUPER. Depois, consulte o elemento desejado usando a sintaxe value.attribute
. Para ter mais informações sobre como consultar elementos de matriz em valores SUPER, acesse Consultar dados semiestruturados.
A função JSON_EXTRACT_PATH_TEXT retorna o valor para o par de chave-valor referido por uma série de elementos de caminho em uma string JSON. O caminho JSON pode ser aninhado em até cinco níveis de profundidade. Os elementos do caminho diferenciam maiúsculas e minúsculas. Se um elemento do caminho não existir na string JSON, JSON_EXTRACT_PATH_TEXT retornará NULL
.
Se o argumento null_if_invalid for definido como TRUE
e a string JSON for inválida, a função retornará NULL
, em vez de retornar um erro.
JSON_EXTRACT_PATH_TEXT tem um tamanho máximo de dados de 64 KB. Portanto, se algum registro JSON for maior que 64 KB, processá-lo com JSON_EXTRACT_PATH_TEXT vai gerar um erro.
Para obter informações sobre outras funções JSON, consulte Funções JSON. Para obter mais informações sobre como trabalhar com JSON, consulte COPY no formato JSON.
Sintaxe
JSON_EXTRACT_PATH_TEXT('json_string', 'path_elem' [,'path_elem'[, …] ] [, null_if_invalid ] )
Argumentos
- json_string
-
Uma string JSON adequadamente formatada.
- path_elem
-
Um elemento de caminho em uma string JSON. Um elemento de caminho é obrigatório. Elementos de caminho adicionais podem ser especificados com até cinco níveis de profundidade.
- null_if_invalid
-
(Opcional) Um valor
BOOLEAN
que especifica seNULL
será ou não retornado caso a string de entrada JSON seja inválida, em vez de retornar um erro. Para retornarNULL
se JSON for inválido, especifiqueTRUE
(t
). Para retornar um erro se JSON for inválido, especifiqueFALSE
(f
). O padrão éFALSE
.
Em uma string JSON, o Amazon Redshift reconhece \n
como um caractere de nova linha e \t
como um caractere de tabulação. Para carregar uma barra invertida, use uma barra invertida de escape (\\
). Para obter mais informações, consulte Caracteres de escape em JSON.
Tipo de retorno
VARCHAR
-
Uma string
VARCHAR
representando o valor JSON referido pelos elementos de caminho.
Exemplos
Para retornar o valor do caminho 'f4', 'f6'
, use o exemplo a seguir.
SELECT JSON_EXTRACT_PATH_TEXT('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}}','f4', 'f6');
+------------------------+ | json_extract_path_text | +------------------------+ | star | +------------------------+
Para retornar um erro porque JSON é inválido, use o exemplo a seguir.
SELECT JSON_EXTRACT_PATH_TEXT('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}','f4', 'f6');
ERROR: invalid json object {"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}
Para definir null_if_invalid como TRUE a fim de que a instrução retorne NULL
para o JSON inválido em vez de retornar um erro, use o exemplo a seguir.
SELECT JSON_EXTRACT_PATH_TEXT('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}','f4', 'f6',true);
+------------------------+ | json_extract_path_text | +------------------------+ | NULL | +------------------------+
Considere o exemplo a seguir, que seleciona o valor para o caminho 'farm', 'barn', 'color'
, em que o valor recuperado está no terceiro nível, use o exemplo a seguir. Esse exemplo é formatado com uma ferramenta JSON Lint para facilitar a leitura.
SELECT JSON_EXTRACT_PATH_TEXT('{ "farm": { "barn": { "color": "red", "feed stocked": true } } }', 'farm', 'barn', 'color');
+------------------------+ | json_extract_path_text | +------------------------+ | red | +------------------------+
Para retornar NULL
porque o elemento 'color'
está ausente, use o exemplo a seguir. Esse exemplo é formatada com uma ferramenta JSON Lint.
SELECT JSON_EXTRACT_PATH_TEXT('{ "farm": { "barn": {} } }', 'farm', 'barn', 'color');
+------------------------+ | json_extract_path_text | +------------------------+ | NULL | +------------------------+
Se o JSON for válido, tentar extrair um elemento ausente retornará NULL
.
Para retornar o valor do caminho 'house', 'appliances', 'washing machine', 'brand'
, use o exemplo a seguir.
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 | +------------------------+
O exemplo abaixo cria uma tabela de exemplo e a preenche com valores SUPER e, em seguida, retorna o valor do caminho 'f2'
para ambas as linhas.
CREATE TABLE json_example(id INT, json_text SUPER); INSERT INTO json_example VALUES (1, JSON_PARSE('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}}')), (2, JSON_PARSE('{ "farm": { "barn": { "color": "red", "feed stocked": true } } }')); SELECT * FROM json_example;
id | json_text ------------+-------------------------------------------- 1 | {"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}} 2 | {"farm":{"barn":{"color":"red","feed stocked":true}}}
SELECT id, JSON_EXTRACT_PATH_TEXT(JSON_SERIALIZE(json_text), 'f2') FROM json_example;id | json_text ------------+-------------------------------------------- 1 | {"f3":1} 2 |
Considere o exemplo de declarações a seguir. O path_elem fornecido é NULL, então JSON_EXTRACT_PATH_TEXT retorna NULL independentemente do valor de qualquer outro parâmetro.
--Statement where path_elem is NULL and json_string is valid JSON. SELECT JSON_EXTRACT_PATH_TEXT('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}}',NULL);
json_extract_path_text ------------------------ NULL
--Statement where only one path_elem is NULL. SELECT JSON_EXTRACT_PATH_TEXT('{"f2":{"f3":1},"f4":{"f5":99,"f6":"star"}}','f4',NULL);json_extract_path_text ------------------------ NULL
--Statement where path_elem is NULL and json_string is invalid JSON. SELECT json_extract_path_text('invalid_json', NULL);json_extract_path_text ------------------------ NULL
--Statement where path_elem is NULL and null_if_invalid is FALSE. SELECT json_extract_path_text(NULL, 0, FALSE);json_extract_path_text ------------------------ NULL
Considere o exemplo de declarações a seguir. Quando null_if_invalid é TRUE, JSON_EXTRACT_PATH_TEXT retorna NULL quando json_string é um JSON inválido. Se null_if_invalid for FALSE ou não estiver definido, a função retornará um erro quando json_string for inválido.
--Statement with invalid JSON where null_if_invalid is TRUE. SELECT json_extract_path_text('invalid_json', 0, TRUE);
json_extract_path_text ------------------------ NULL
--Statement with invalid JSON where null_if_invalid is FALSE. SELECT json_extract_path_text('invalid_json', 0, FALSE);ERROR: JSON parsing error
Considere os exemplos a seguir, em que json_string é um JSON válido e path_elem se refere a um valor JSON null
. Nesse caso, JSON_EXTRACT_PATH_TEXT retorna NULL. Da mesma forma, quando path_elem se refere a um valor não existente, JSON_EXTRACT_PATH_TEXT retorna NULL, independentemente do valor de null_if_invalid.
--Statement selecting a null value. SELECT json_extract_path_text('[null]', 0); json_extract_path_text ------------------------- NULL --Statement selecting a non-existing value. SELECT json_extract_path_text('{}', 'a'); json_extract_path_text ------------------------- NULL