

 O Amazon Redshift não permitirá mais a criação de UDFs do Python a partir do Patch 198. As UDFs do Python existentes continuarão a funcionar normalmente até 30 de junho de 2026. Para ter mais informações, consulte a [publicação de blog ](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/). 

# Função JSON\$1EXTRACT\$1PATH\$1TEXT
<a name="JSON_EXTRACT_PATH_TEXT"></a>

**nota**  
O JSON\$1PARSE 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\$1EXTRACT\$1PATH\$1TEXT, recomendamos que você analise suas strings JSON usando o [Função JSON\$1PARSE](JSON_PARSE.md) 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](query-super.md).

A função JSON\$1EXTRACT\$1PATH\$1TEXT 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\$1EXTRACT\$1PATH\$1TEXT retornará `NULL`.

Se o argumento *null\$1if\$1invalid* for definido como `TRUE` e a string JSON for inválida, a função retornará `NULL`, em vez de retornar um erro.

JSON\$1EXTRACT\$1PATH\$1TEXT tem um tamanho máximo de dados de 64 KB. Portanto, se algum registro JSON for maior que 64 KB, processá-lo com JSON\$1EXTRACT\$1PATH\$1TEXT vai gerar um erro. 

Para obter informações sobre outras funções JSON, consulte [Funções JSON](json-functions.md). Para obter mais informações sobre como trabalhar com JSON, consulte [COPY no formato JSON](copy-usage_notes-copy-from-json.md).

## Sintaxe
<a name="JSON_EXTRACT_PATH_TEXT-synopsis"></a>

```
JSON_EXTRACT_PATH_TEXT('json_string', 'path_elem' [,'path_elem'[, …] ] [, null_if_invalid ] )
```

## Argumentos
<a name="JSON_EXTRACT_PATH_TEXT-arguments"></a>

 *json\$1string*  
Uma string JSON adequadamente formatada.

*path\$1elem*  
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\$1if\$1invalid*  
(Opcional) Um valor `BOOLEAN` que especifica se `NULL` será ou não retornado caso a string de entrada JSON seja inválida, em vez de retornar um erro. Para retornar `NULL` se JSON for inválido, especifique `TRUE` (`t`). Para retornar um erro se JSON for inválido, especifique `FALSE` (`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](copy-usage_notes-copy-from-json.md#copy-usage-json-escape-characters).

## Tipo de retorno
<a name="JSON_EXTRACT_PATH_TEXT-return"></a>

`VARCHAR`  
Uma string `VARCHAR` representando o valor JSON referido pelos elementos de caminho.

## Exemplos
<a name="JSON_EXTRACT_PATH_TEXT-examples"></a>

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\$1if\$1invalid* 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\$1elem* fornecido é NULL, então JSON\$1EXTRACT\$1PATH\$1TEXT 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\$1if\$1invalid* é TRUE, JSON\$1EXTRACT\$1PATH\$1TEXT retorna NULL quando *json\$1string* é um JSON inválido. Se *null\$1if\$1invalid* for FALSE ou não estiver definido, a função retornará um erro quando *json\$1string* 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\$1string* é um JSON válido e *path\$1elem* se refere a um valor JSON `null`. Nesse caso, JSON\$1EXTRACT\$1PATH\$1TEXT retorna NULL. Da mesma forma, quando *path\$1elem* se refere a um valor não existente, JSON\$1EXTRACT\$1PATH\$1TEXT retorna NULL, independentemente do valor de *null\$1if\$1invalid*.

```
--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
```