# Stringify Data

> 将结构化数据对象序列化为字符串格式。

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

- 标识: `data.stringify`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

将结构化数据对象序列化为字符串格式。

它是“Parse Data”的逆操作。当你需要把 JSON 对象作为原始字符串请求体发送给 API、将配置保存到文本文件，或根据条目列表生成 CSV 报表时，它非常有用。

**支持的格式：**
- **JSON：** 标准 JSON 序列化（可选美化输出）。
- **CSV：** 将对象列表转换为逗号分隔值。
- **XML：** 将对象树转换为 XML。
- **YAML：** 将对象转换为 YAML。

**适用场景：**
- 为 `http.request` 准备请求体载荷。
- 生成可下载的 CSV 导出文件。

## 配置

- `format` (string, 可选): 默认值: `json`. 可选值: `json`, `csv`, `xml`, `yaml`.
- `pretty` (boolean, 可选): 为 true 时添加缩进/换行（仅 JSON/XML）。 默认值: `false`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): Serialized
- `error`: Error

## 输入契约

- `data` (any, 必填): 要序列化的数据结构。

## 输出契约

- `string` (string, 可选): 序列化后的字符串。

## 在表达式中

后续节点可通过 `$("Stringify Data").item.json.<路径>` 读取此节点输出中的内容（请把 `Stringify Data` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Stringify Data").item.json.string` (string) = `"{\"order_id\":\"ord_123\",\"total\":42.5}"`: 序列化后的字符串。


## 工作原理

将整个输入 payload 序列化为 JSON、CSV、XML 或 YAML，并以 `{ string }` 返回。

1. 解析配置；`format` 默认 `json`，`pretty` 默认 false。没有用于选择字段的键：输入始终是整个 payload。
2. `json`：`JSON.stringify`，`pretty` 为 true 时缩进 2 个空格。
3. `csv`：payload 必须是对象数组，或所有值都是对象的对象。表头取第一行的键；每个值按 JSON 编码（字符串加双引号，`null` 为 `""`，缺失为空）；行之间用 `\n` 连接。
4. `xml`：使用 fast-xml-parser 的 `XMLBuilder`，外层包裹 `<root>`；`pretty` 会缩进输出。
5. `yaml`：js-yaml 块样式，`pretty` 为 true 时缩进 4 个空格，否则 2 个。
6. 通过 `out` 返回 `{ string }`。未知的 `format` 返回 `String(payload)`。

## 在工作流中

### 节点

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

## 输出端口 (代码中的行为)

### `out`

序列化完成。

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

### `error`

序列化器抛出异常。

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

## 代码中的行为

- `pretty`: 也会影响 `yaml`（缩进 4），而不只是 schema 所说的 JSON 和 XML。
- `format`: `csv` 遇到非表格 payload（例如 `{}` 或值为标量的对象）时，通过 `out` 返回 `"[object Object]"`，而不是报错。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Stringify Error: <message>` | `error` | XML 或 YAML 库无法序列化该 payload。 |

## 说明与限制

- CSV 列只取自第一行：仅在后续行出现的键会被丢弃。
- 输入契约写的是 `data`，但实际序列化的是整个 payload。若只需某个字段，请先用 `data.transform` 整理。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（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"
  }
]
```
