# Stringify Data

> Serializa un objeto de datos estructurado en una cadena.

Source: https://docs.sommatic.ai/es/nodes/data.stringify/

- Slug: `data.stringify`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Serializa un objeto de datos estructurado en una cadena.

Es la operación inversa de 'Parse Data'. Resulta útil cuando necesitas enviar un objeto JSON como cuerpo en bruto a una API, guardar una configuración en un archivo de texto o generar un reporte CSV a partir de una lista de elementos.

**Formatos admitidos:**
- **JSON:** Serialización JSON estándar (con formato legible opcional).
- **CSV:** Convierte una lista de objetos en valores separados por comas.
- **XML:** Convierte un árbol de objetos en XML.
- **YAML:** Convierte un objeto en YAML.

**Casos de uso:**
- Preparar el payload para el cuerpo de un `http.request`.
- Generar una exportación CSV descargable.

## Configuración

- `format` (string, opcional): Por defecto: `json`. Valores permitidos: `json`, `csv`, `xml`, `yaml`.
- `pretty` (boolean, opcional): Si es true, agrega sangría y saltos de línea (solo JSON/XML). Por defecto: `false`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Serialized
- `error`: Error

## Contrato de entrada

- `data` (any, obligatorio): La estructura de datos que se serializa.

## Contrato de salida

- `string` (string, opcional): La cadena serializada.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Stringify Data").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Stringify Data`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Stringify Data").item.json.string` (string) = `"{\"order_id\":\"ord_123\",\"total\":42.5}"`: La cadena serializada.


## Cómo funciona

Serializa el payload de entrada completo a JSON, CSV, XML o YAML y lo devuelve como `{ string }`.

1. Resuelve la configuración; `format` vale `json` y `pretty` false por defecto. No hay clave para elegir un campo: la entrada siempre es el payload completo.
2. `json`: `JSON.stringify`, con sangría de 2 espacios cuando `pretty` es true.
3. `csv`: el payload debe ser un arreglo de objetos, o un objeto cuyos valores sean todos objetos. La fila de encabezado son las claves de la primera fila; cada valor se codifica como JSON (cadenas entre comillas dobles, `null` como `""`, ausentes vacíos); las filas se unen con `\n`.
4. `xml`: `XMLBuilder` de fast-xml-parser, envuelto en `<root>`; `pretty` agrega sangría.
5. `yaml`: js-yaml en estilo de bloque, con sangría de 4 espacios cuando `pretty` es true y de 2 en otro caso.
6. Devuelve `{ string }` por `out`. Un `format` desconocido devuelve `String(payload)`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-to-json",
  "label": "Serialize order",
  "operator_slug": "data.stringify",
  "operator_version": "1.0.0",
  "config": {
    "format": "json",
    "pretty": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "string": "{\"order_id\":\"ord_123\",\"total\":42.5}"
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

La serialización terminó.

```json
{
  "string": "{\"order_id\":\"ord_123\",\"total\":42.5}"
}
```

### `error`

El serializador lanzó un error.

```json
{
  "ok": false,
  "errors": [
    "Stringify Error: <message>"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `pretty`: También afecta a `yaml` (sangría 4), no solo a JSON y XML como dice el esquema.
- `format`: `csv` con un payload que no es tabular (por ejemplo `{}` o un objeto con valores escalares) devuelve `"[object Object]"` por `out`, no un error.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Stringify Error: <message>` | `error` | La biblioteca de XML o YAML no pudo serializar el payload. |

## Notas y límites

- Las columnas CSV salen solo de la primera fila: las claves que aparecen solo en filas posteriores se pierden.
- El contrato de entrada menciona `data`, pero se serializa el payload completo. Dale forma antes con `data.transform` si necesitas un solo campo.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.stringify",
  "name": "Stringify Data",
  "category": "data",
  "version": "1.0.0",
  "description": "Serializes a structured data object into a string format.\n\n  This is the inverse of 'Parse Data'. It is useful when you need to send a JSON object as a raw string body to an API, save a configuration to a text file, or generate a CSV report from a list of items.\n\n  **Supported Formats:**\n  - **JSON:** Standard JSON serialization (with optional pretty-print).\n  - **CSV:** Converts a list of objects to Comma-Separated Values.\n  - **XML:** Converts an object tree to XML.\n  - **YAML:** Converts an object to YAML.\n\n  **Use Cases:**\n  - preparing a payload for an `http.request` body.\n  - Generating a downloadbale CSV export.",
  "capabilities": [
    "serialization",
    "format-conversion",
    "transform"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "format": {
        "type": "string",
        "enum": [
          "json",
          "csv",
          "xml",
          "yaml"
        ],
        "default": "json",
        "title": "Target Format"
      },
      "pretty": {
        "type": "boolean",
        "default": false,
        "title": "Pretty Print",
        "description": "If true, adds indentation/newlines (JSON/XML only)."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "data": {
        "type": "any",
        "description": "The data structure to serialize."
      }
    },
    "required": [
      "data"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "string": {
        "type": "string",
        "description": "The serialized string."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Serialized",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "serialization",
    "json",
    "csv",
    "xml"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "format": {
      "type": "string",
      "enum": [
        "json",
        "csv",
        "xml",
        "yaml"
      ],
      "default": "json",
      "title": "Target Format"
    },
    "pretty": {
      "type": "boolean",
      "default": false,
      "title": "Pretty Print",
      "description": "If true, adds indentation/newlines (JSON/XML only)."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "data": {
      "type": "any",
      "description": "The data structure to serialize."
    }
  },
  "required": [
    "data"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "string": {
      "type": "string",
      "description": "The serialized string."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Serialized",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
