---
sourceDocument: Referência de API do Xanadu
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/pt-BR/xanadu/api-reference

 Release :

    - xanadu

ft:locale :

    - pt-BR

ft:publication_title :

    - Referência de API do Xanadu

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Transformador - com escopo, global

# Transformador - com escopo, global {#ariaid-title1}

* Versão de lançamento: Xanadu
* 
* Atualizado 1 de ago. de 2024
* 
* ![](https://www.servicenow.com/docs/portal-asset/ico-clock) 4 min. de leitura

A API do transformador fornece métodos para analisar e transformar conteúdo de origem JSON ou XML estruturado em saída de par de chave-valor estruturado, usando um conjunto definido de regras.

Esta API funciona junto com as APIs TransformerDefinition e TransformerRuleList. Juntos, essas APIs transformam nós XML ou qualquer entidade em um documento JSON estruturado em uma saída de pares de nome-valor. Entidades JSON compatíveis, incluindo objetos e elementos em uma matriz, como cadeias de caracteres, números e outras matrizes.  
* A API TransformerRuleList permite criar listas de regras de transformação que definem quais dados no documento de origem serão incluídos na saída e como transformar os dados de origem.

* A API TransformerDefinition associa uma lista de regras de transformação a um caminho de registro JSON/XML para definir objetos de definição de transformação reutilizáveis. Você pode usar um objeto de definição de transformação para transformar um ou mais documentos de origem.

* A API do transformador executa a transformação de dados real, uma entidade de dados de cada vez, usando a lista de regras de transformação especificada para criar os dados de saída desejados.

{#TransformerScriptedAPI__ul_nsk_xfv_bkb}

Você pode usar a classe Transformador em scripts de servidor com escopo e globais. Ao usar esta classe, use o identificador de namespace `sn_tfrm`. Antes que esta API esteja disponível em uma instância, você deve ativar o plug-in Serviço de transformação (com.glide.transform).

O exemplo a seguir ilustra como usar a API TransformerRuleList para definir as regras de transformação, a API TransformerDefinition para definir os critérios de transformação e a API Transformer para executar a transformação.

Este exemplo de código recupera um documento externo de detalhes do estoque baseado em JSON, cria regras para transformar esses dados em uma tabela tabular e transforma o documento de origem, uma linha de cada vez. A seguir está um snippet do documento de origem JSON que está sendo transformado:  

    {
      "NOW": {
        "quote": {
          "symbol": "NOW",
          "companyName": "ServiceNow Inc.",
          "primaryExchange": "New York Stock Exchange",
          "sector": "Technology",
          "open": 166.78,
          "openTime": 1522935000556,
          "close": 165.77,
          "changePercent": 0.00656,
           ...
         },
     ...}

    var stockAPI = new sn_ws.RESTMessageV2('Stock Details', 'Default GET'); 
    var response = stockAPI.execute(); 
    var responseBody = response.getBody(); // obtain the source JSON document

    /* Define the list of rules to use to transform the acquired JSON stock detail 
    information into a tabular table */

    var transformerRuleList = new sn_tfrm.TransformerRuleList() // instantiate the rule list object
      .fromJSON() // indicate that the source document is JSON
      .addRule('ticker', '$.quote.symbol') // add a rule to copy the value in the "symbol" field of the source document to the ticker field in the output document (no changes)
      .addRule('change_percentage', '$.quote.changePercent') // copy the "changePercent" field from source into the change_percentage field of output document
      .thenMultiply('100') // multiply the change_percentage value by 100
      .thenRoundDown('0') // addthen round it down to a whole number 
      .addRule('close_price', '$.quote.close') // copy the "close" field to the close_price field in the 21=-[';output
      .thenAdaptCurrency('USD', false) // attach the US dollar code to the close_price field, but do not display the symbol
      .addRule('summary') // add a blank "summary" field to the output (no corresponding source field)
      .thenConcat('Shares of ') // in the summary field concatenate the string "Shares of "
      .thenConcatSymbol('ticker') // then concatenate the "ticker" field from the source document
      .thenConcat(' closed at ') // then concatenate the string " closed at "
      .thenConcatSymbol('close_price'); // then concatenate the "close_price" field from the source document

    // Create a transformer definition that associates the rule list to use and the record path of the set of records in the source document to transform.  
    var path = '$.*'; 
    var transformerDefinition = new sn_tfrm.TransformerDefinition(transformerRuleList, path);
     
    // Instantiate the transformer object.
    var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody); 

    // Transform the source data, one row at a time, until all rows are processed.
    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    } 

Saída:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }

## Transformador - Transformador (TransformerDefinition de objeto, Documento de cadeia de caracteres) {#ariaid-title2}

Instancia um objeto Transformador (construtor).
{#Trans-Transformer_O_S__table_uq2_glh_phb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| TransformadorDefinição | Objeto | Objeto que descreve a transformação do conteúdo; inclui a lista de regras e o caminho do registro JSONPath/XPath. Use as APIs TransformerRuleList() e TransformerDefinition() para gerar este objeto. |
| documento | Cadeia de caracteres | Documento de origem a ser traduzido. |
[Tabela 1. Parâmetros]

{#Trans-Transformer_O_S__table_uq2_glh_phb}  

    var stockAPI = new sn_ws.RESTMessageV2('Stock Details', 'Default GET'); 
    var response = stockAPI.execute(); 
    var responseBody = response.getBody(); 

    var transformerRuleList = new sn_tfrm.TransformerRuleList()
      .fromJSON()
      .addRule('ticker', 'quote.symbol') 
      .addRule('change_percentage', 'quote.change') 
      .thenMultiply('100') 
      .thenRoundDown('0') 
      .addRule('close_price', 'quote.close') 
      .thenAdaptCurrency('USD', false) 
      .addRule('summary') 
      .thenConcat('Shares of ') 
      .thenConcatSymbol('ticker') 
      .thenConcat(' closed at ') 
      .thenConcatSymbol('close') 

     
    var path = '$.*'; 
    var transformerDefinition = new sn_tfrm.TransformerDefinition(transformerRuleList, path); 
    var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody); 

    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());
    }

## Transformador - getRow() {#ariaid-title3}

Retorna a linha resultante da última transformação (ou nula se não existir nenhuma linha).
{#Trans-getRow__table_gyt_trh_phb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| Nenhum |   |   |
[Tabela 2. Parâmetros]

{#Trans-getRow__table_gyt_trh_phb} {#Trans-getRow__table_hyt_trh_phb__entry__2}

| Tipo | Descrição |
|-|-|
| Objeto | Objeto que contém uma linha/nó transformado de dados. |
[Tabela 3. Retorna]

{#Trans-getRow__table_hyt_trh_phb}  

    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());

Saída:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }

## Transformador - transform() {#ariaid-title4}

Transforma a próxima linha/nó disponível no documento de origem.
{#Trans-transform__table_kjw_tph_phb__entry__3}

| Nome | Tipo | Descrição |
|-|-|-|
| Nenhum |   |   |
[Tabela 4. Parâmetros]

{#Trans-transform__table_kjw_tph_phb} {#Trans-transform__table_ljw_tph_phb__entry__2}

| Tipo | Descrição |
|-|-|
| Booliano | Sinalizador que indica se há uma próxima linha válida a ser transformada. * verdadeiro: próxima linha válida * falso: não há linhas adicionais {#Trans-transform__ul_zcn_2qh_phb} |
[Tabela 5. Retorna]

{#Trans-transform__table_ljw_tph_phb}  

    var results = []; 
    while (transformer.transform()) { 
      results.push(transformer.getRow());

Saída:

     {ticker: "Now", change_percentage: "0", close_price: "165.77 USD", summary: "Shares of Now closed at 165.77" }


