# Funções de JSON

As funções de JSON realizam operações em objetos do tipo JSON e estão disponíveis para componentes que suportam expressões com *Double Braces*. Para saber como passar informações para os componentes utilizando esse recurso, leia a documentação [Funções *Double Braces*](https://docs.digibee.com/documentation/connectors-and-triggers/pt-br/double-braces/double-braces-functions).

## JSONPATH

Essa função retorna partes de um determinado documento conforme a expressão enviada.

### Sintaxe

```json
JSONPATH(value:string, expression:string)
```

* **value:** *string*
* **expression:** *string* contendo a expressão a ser recuperada

Digamos que você precise obter parte de um documento utilizando expressões. O documento contém as seguintes informações, que podem ser passadas pelo último componente do fluxo ou pelo *payload*:

```json
{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ]
  }
}
```

Conseguindo a informação:

```json
{
  "test": {{ JSONPATH(message.$, "$.store.book[?(@.price > 10)]") }},
  "test2": {{ JSONPATH(message.store.book,"$.[0]" ) }}
}
```

O resultado esperado será:

```json
{
  "test": [
    {
      "category": "fiction",
      "author": "Evelyn Waugh",
      "title": "Sword of Honour",
      "price": 12.99
    },
    {
      "category": "fiction",
      "author": "J. R. R. Tolkien",
      "title": "The Lord of the Rings",
      "isbn": "0-395-19395-8",
      "price": 22.99
    }
  ],
  "test2": {
    "category": "reference",
    "author": "Nigel Rees",
    "title": "Sayings of the Century",
    "price": 8.95
  }
}
```

É possível utilizar as próprias funções que o JSONPATH provê internamente, tais como:

* `min()`
* `max()`
* `avg()`
* `stddev()`
* `length`

#### Exemplo

Suponha que um *array* de entrada seja recebido:

```json
{
  "numbers": [
    1,
    33,
    56,
    77.8,
    66,
    10475,
    665464,
    1,
    0.01
  ]
}
```

E que você queira utilizar as funções descritas acima no campo “*expression*”:

```json
{
  "min": {{ JSONPATH(message.numbers, "$.min()") }},
  "max": {{ JSONPATH(message.numbers, "$.max()") }},
  "avg": {{ JSONPATH(message.numbers, "$.avg()") }},
  "stddev": {{ JSONPATH(message.numbers, "$.stddev()") }},
  "length": {{ JSONPATH(message.numbers, "$.length()") }}
}
```

O resultado será:

```json
{
  "min": 0.01,
  "max": 665464.0,
  "avg": 75130.42333333334,
  "stddev": 208739.83034832493,
  "length": 9
}
```

## TOJSON

Essa função retorna o valor do JSON a partir do objeto recebido.

### Sintaxe

```json
TOJSON(value:string)
```

* value: string

Digamos que você precise obter os valores em um objeto JSON. Você pode fazer o seguinte:

```json
{ 
  "test1": {{ TOJSON(111) }},
  "test2": {{ TOJSON("false") }},
  "test3": {{ TOJSON("{\"name\":\"John\",\"age\":31,\"city\":\"New York\"}") }},
  "test4": {{ TOJSON(null) }}
}
```

O resultado esperado será:

```json
{
  "test1": 111,
  "test2": false,
  "test3": {
    "name": "John",
    "age": 31,
    "city": "New York"
  },
  "test4": null
}
```

## UNESCAPEJSON

Essa função retorna um JSON removendo os *escapes* encontrados no valor fornecido.

### Sintaxe

```json
UNESCAPE(value:string, type:optional)
```

* **value:** *string*
* **type (opcional):** CSV, HTML, XML e JSON. O valor padrão é JSON.

Digamos que você precise remover caracteres de *escape* do seguinte *payload*:

{% code overflow="wrap" %}

```json
{
  "jsonEscaped": "{\\\"name\\\":\\\"John\\\",\\\"age\\\":31,\\\"city\\\":\\\"New York\\\"}"
}
```

{% endcode %}

Removendo os caracteres de *escape*:

```json
{
  "unescaped": {{ UNESCAPEJSON(message.jsonEscaped) }}
} 
```

O resultado esperado será:

```json
{
  "unescaped": "{\"name\":\"John\",\"age\":31,\"city\":\"New York\"}"
}
```

## GETELEMENTAT

Essa função permite que você capture um elemento específico de um *array*.

### Sintaxe

```json
GETELEMENTAT(array, índice)
```

Vamos supor que você precise capturar o primeiro elemento do *array* abaixo:

```json
{
  "data": [
    {
      "field": "value-1"
    },
    {
      "field": "value-2"
    },
    {
      "field": "value-3"
    }
  ]
}
```

Capturando o elemento:

```json
{
  "element": {{ GETELEMENTAT(message.data, 0) }}
}
```

O resultado será:

```json
{
  "element": {
    "field": "value-1"
  }
}
```

Se a função receber um índice inexistente, o valor `null` será retornado.

## LASTELEMENT

Essa função permite que você capture o último elemento de um *array*.

### Sintaxe

```json
LASTELEMENT(array)
```

Vamos supor que você precise capturar o último elemento do *array* abaixo:

```json
{
  "data": [
    {
      "field": "value-1"
    },
    {
      "field": "value-2"
    },
    {
      "field": "value-3"
    }
  ]
}
```

Capturando o elemento:

```json
{
  "element": {{ LASTELEMENT(message.data) }}
}
```

O resultado será:

```json
{
  "element": {
    "field": "value-3"
  }
}
```

Se a função receber um array vazio, o valor `null` será retornado.

## REMOVEAT

Essa função permite que você remova um elemento específico de um *array*.

### Sintaxe

```json
REMOVEAT(array, index)
```

Vamos supor que você precise remover o segundo elemento do *array* abaixo:

```json
{
  "data": [
    {
      "field": "value-1"
    },
    {
      "field": "value-2"
    },
    {
      "field": "value-3"
    }
  ]
}
```

Removendo o elemento:

```json
{
  "data": {{ REMOVEAT(message.data, 1) }}
}
```

O resultado será:

```json
{
  "data": [
    {
      "field": "value-1"
    },
    {
      "field": "value-3"
    }
  ]
}
```

Se a função receber um índice inexistente, o *array* original será retornado sem alterações.

## PUSH

Essa função permite que você insira um elemento no final de um *array*.

### Sintaxe

```json
PUSH(array, element)
```

Vamos supor que você precise inserir um novo elemento no *array* abaixo:

```json
{
  "element": {
    "example": "123"
  },
  "array": [
    {
      "example": "ABC"
    },
    {
      "example": "FFF"
    }
  ]
}
```

Inserindo o novo elemento:

```json
{
  "array": {{ PUSH(message.array, message.element) }}
}
```

O resultado será:

```json
{
  "array": [
    {
      "example": "ABC"
    },
    {
      "example": "FFF"
    },
    {
      "example": "123"
    }
  ]
}
```

Se a função receber um elemento inexistente ou nulo, o valor `null` será inserido no final do *array*.

## POP

Essa função permite que você remova o último elemento de um *array*, retornando o elemento removido e o *array* remanescente.

### Sintaxe

```json
POP(array)
```

Vamos supor que você precise remover o último elemento do *array* abaixo:

```json
{
  "array": [
    {
      "id": "ABC"
    },
    {
      "id": "FFF"
    },
    {
      "id": "123"
    }
  ]
}
```

Removendo o último elemento:

```json
{
  "data": {{ POP(message.array) }}
}
```

O resultado será:

```json
{
  "data": {
    "array": [
      {
        "id": "ABC"
      },
      {
        "id": "FFF"
      }
    ],
    "element": {
      "id": "123"
    }
  }
}
```

Se a função receber um *array* vazio, o mesmo *array* vazio será retornado.

## NEWEMPTYOBJECT

Essa função permite que você crie um novo objeto vazio.

### Sintaxe

```json
NEWEMPTYOBJECT()
```

Vamos supor que você precise criar um novo objeto vazio:

```json
{
  "data": {
    
  }
}
```

Criando:

```json
{
  "data": {{ NEWEMPTYOBJECT() }}
}
```

O resultado será:

```json
{
  "data": {
    
  }
}
```

## NEWEMPTYARRAY

Essa função permite que você crie um novo *array* vazio.

### Sintaxe

```json
NEWEMPTYARRAY()
```

Digamos que você precise criar um novo array vazio:

```json
{
  "data": [
    
  ]
}
```

Criando:

```json
{
  "data": {{ NEWEMPTYARRAY() }}
}
```

O resultado será:

```json
{
  "data": [
    
  ]
}
```

## CARDINALITYONE

Essa função possibilita aplicar uma cardinalidade de n:1 na estrutura informada, onde independente da quantidade de elementos na entrada, a saída será sempre 1 elemento.

### Sintaxe

```json
CARDINALITYONE(data)
```

Digamos que você precise aplicar a cardinalidade n:1 em cada elemento do JSON abaixo:

```json
{
  "arrayObject": [
    {
      "id": "PROD-123",
      "type": "Product"
    },
    {
      "id": "CUST-456",
      "type": "Customer"
    }
  ],
  "arrayNumber": [
    23,
    790
  ],
  "emptyArray": [
    
  ],
  "object": {
    "test": "value"
  },
  "singleNumber": 500,
  "singleString": "CARDINALITY",
  "nullValue": null,
  "emptyObject": {
    
  }
}
```

Aplicando a função:

```json
{
  "arrayObject": {{ CARDINALITYONE(message.arrayObject) }},
  "arrayNumber": {{ CARDINALITYONE(message.arrayNumber) }},
  "emptyArray": {{ CARDINALITYONE(message.emptyArray) }},
  "object": {{ CARDINALITYONE(message.object) }},
  "singleNumber": {{ CARDINALITYONE(message.singleNumber) }},
  "singleNumber": {{ CARDINALITYONE(message.singleNumber) }},
  "singleString": {{ CARDINALITYONE(message.singleString) }},
  "emptyObject": {{ CARDINALITYONE(message.emptyObject) }}
}
```

O resultado será:

```json
{
  "arrayObject": {
    "id": "PROD-123",
    "type": "Product"
  },
  "arrayNumber": 23,
  "emptyArray": null,
  "object": {
    "test": "value"
  },
  "singleNumber": 500,
  "singleString": "CARDINALITY",
  "emptyObject": {
    
  }
}
```

## CARDINALITYMANY

Essa função possibilita normalizar a saída em cardinalidade múltipla. Ou seja, caso a entrada seja um *array* com n elementos, a saída será um *array* com n elementos e caso a entrada seja um único objeto, a saída será um *array* contendo este único objeto.

### Sintaxe

```json
CARDINALITYMANY(data)
```

Digamos que você precise aplicar a cardinalidade m:n em cada elemento do JSON abaixo:

```json
{
  "arrayObject": [
    {
      "id": "PROD-123",
      "type": "Product"
    },
    {
      "id": "CUST-456",
      "type": "Customer"
    }
  ],
  "arrayNumber": [
    23,
    790
  ],
  "emptyArray": [
    
  ],
  "object": {
    "test": "value"
  },
  "singleNumber": 500,
  "singleString": "CARDINALITY",
  "nullValue": null,
  "emptyObject": {
    
  }
}
```

Aplicando a função:

```json
{
  "arrayObject": {{ CARDINALITYMANY(message.arrayObject) }},
  "arrayNumber": {{ CARDINALITYMANY(message.arrayNumber) }},
  "emptyArray": {{ CARDINALITYMANY(message.emptyArray) }},
  "object": {{ CARDINALITYMANY(message.object) }},
  "singleNumber": {{ CARDINALITYMANY(message.singleNumber) }},
  "singleNumber": {{ CARDINALITYMANY(message.singleNumber) }},
  "singleString": {{ CARDINALITYMANY(message.singleString) }},
  "emptyObject": {{ CARDINALITYMANY(message.emptyObject) }}
}
```

O resultado será:

```json
{
  "arrayObject": [
    {
      "id": "PROD-123",
      "type": "Product"
    },
    {
      "id": "CUST-456",
      "type": "Customer"
    }
  ],
  "arrayNumber": [
    23,
    790
  ],
  "emptyArray": [
    
  ],
  "object": [
    {
      "test": "value"
    }
  ],
  "singleNumber": [
    500
  ],
  "singleString": [
    "CARDINALITY"
  ],
  "emptyObject": [
    {
      
    }
  ]
}
```
