# Parse Data

> 将原始字符串解析为结构化数据对象。

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

- 标识: `data.parse`
- 类别: 数据
- 版本: 1.0.0
- 状态: 部分可用. 仅实现了 `json` 和 `csv`；`xml` 与 `yaml` 会从 `error` 输出（"not supported yet"）。CSV 解析不支持带引号的字段。
- 执行方式: sync

将原始字符串解析为结构化数据对象。

处理来自外部系统、文件或以序列化字符串（JSON、CSV、XML、YAML）返回数据的遗留 API 时必不可少。

**支持的格式：**
- **JSON：** 标准 JSON 解析。
- **CSV：** 逗号分隔值（可输出对象数组）。
- **XML：** 将 XML 转换为 JSON 结构。
- **YAML：** 将 YAML 解析为 JSON。

**适用场景：**
- 将 HTTP 响应正文字符串转换为可用的 JSON 变量。
- 解析用户上传的 CSV 文件。

## 配置

- `input_data` (string, 可选): 要解析的字符串。可用表达式选取特定字段（例如 {{ $json.raw_text }}）。留空则解析整个载荷。
- `format` (string, 可选): 默认值: `json`. 可选值: `json`, `csv`, `xml`, `yaml`.
- `csv_options` (object, 可选)
  - `has_header` (boolean, 可选): 默认值: `true`.
  - `delimiter` (string, 可选): 默认值: `,`.

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

## 输出端口

- `out` (默认): 解析成功。
- `error`: 解析失败（例如 JSON 格式错误）。

## 输入契约

- `raw` (string, 必填): 要解析的原始字符串。

## 输出契约

- `parsed` (any, 可选): 结构化结果（对象/数组）。

## 在表达式中

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

- `$("Parse Data").item.json.parsed` (any): 结构化结果（对象/数组）。 **worker 不返回：读取结果为 undefined.**


## 工作原理

将 JSON 或 CSV 字符串解析为结构化数据，并替换 payload。

1. 解析配置。`input_data` 有值时作为输入，否则使用整个输入 payload。
2. 若输入不是字符串：`format` 为 `json` 且输入为对象时，原样通过 `out` 返回；其他情况失败。
3. `json`：`JSON.parse`；结果（对象、数组或原始值）成为 payload。
4. `csv`：按 `\n` 或 `\r\n` 分行并丢弃空行。`csv_options.has_header`（默认 true）为真时返回以去空白的表头为键的对象数组；否则返回二维数组。值保持为字符串。
5. `xml` 和 `yaml` 已声明但未实现：会失败。

## 在工作流中

### 节点

```json
{
  "node_id": "node-parse-csv",
  "label": "Parse inventory CSV",
  "operator_slug": "data.parse",
  "operator_version": "1.0.0",
  "config": {
    "input_data": "{{ $json.raw_csv }}",
    "format": "csv",
    "csv_options": {
      "has_header": true,
      "delimiter": ","
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": [
    {
      "sku": "A-1",
      "qty": "3"
    },
    {
      "sku": "B-2",
      "qty": "5"
    }
  ],
  "port": "out"
}
```

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

### `out`

解析成功。解析结果就是整个 `data`（此处为带表头的 CSV）。

```json
[
  {
    "sku": "A-1",
    "qty": "3"
  },
  {
    "sku": "B-2",
    "qty": "5"
  }
]
```

### `error`

输入不是字符串、文本格式错误或格式未实现。

```json
{
  "ok": false,
  "errors": [
    "Parse Error (json): Unexpected end of JSON input"
  ],
  "port": "error"
}
```

## 代码中的行为

- `csv_options`: `delimiter`（默认 `,`）和 `has_header`（默认 true）。不处理引号：引号内的分隔符也会切分字段，引号会被保留。行尾缺失的值不会出现在行对象中。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Input data is not a string` | `error` | `input_data` 解析结果不是字符串（或 payload 是对象），且 `format` 不是 `json`。请让 `input_data` 指向文本字段，例如 `{{ $json.raw_csv }}`。 |
| `Parse Error (json): <JSON.parse message>` | `error` | 文本不是有效的 JSON。 |
| `Parse Error (xml): Format xml not supported yet.` | `error` | `xml`（`yaml` 同理）没有解析器。 |

## 说明与限制

- 输出契约中写的是 `parsed`，但解析结果会直接替换 payload。
- 若解析结果为假值（`0`、`false`、`null`、`""`），引擎会改为保存整个信封 `{ ok, data, port }` 作为输出。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

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

```json
{
  "slug": "data.parse",
  "name": "Parse Data",
  "category": "data",
  "version": "1.0.0",
  "description": "Parses a raw string into a structured data object.\n\n  Essential for handling incoming data from external systems, files, or legacy APIs that return data as serialized strings (JSON, CSV, XML, YAML).\n\n  **Supported Formats:**\n  - **JSON:** Standard JSON parsing.\n  - **CSV:** Comma-Separated Values (can output Array of Objects).\n  - **XML:** Converts XML to JSON structure.\n  - **YAML:** Parse YAML to JSON.\n\n  **Use Cases:**\n  - Converting an HTTP response body string into useable JSON variables.\n  - Parsing a CSV file uploaded by a user.",
  "capabilities": [
    "parsing",
    "format-conversion",
    "transform"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "input_data": {
        "type": "string",
        "title": "Input Data",
        "description": "The string to parse. Use expressions to pick a specific field (e.g., {{ $json.raw_text }}). If empty, the entire payload is evaluated."
      },
      "format": {
        "type": "string",
        "enum": [
          "json",
          "csv",
          "xml",
          "yaml"
        ],
        "default": "json",
        "title": "Format"
      },
      "csv_options": {
        "type": "object",
        "properties": {
          "has_header": {
            "type": "boolean",
            "default": true
          },
          "delimiter": {
            "type": "string",
            "default": ","
          }
        }
      },
      "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": {
      "raw": {
        "type": "string",
        "description": "The raw string to parse."
      }
    },
    "required": [
      "raw"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "parsed": {
        "type": "any",
        "description": "The structured result (Object/Array)."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Success",
      "is_default": true,
      "description": "Parsing successful."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Parsing failed (e.g. malformed JSON)."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "json",
    "csv",
    "xml",
    "parser"
  ],
  "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": {
    "input_data": {
      "type": "string",
      "title": "Input Data",
      "description": "The string to parse. Use expressions to pick a specific field (e.g., {{ $json.raw_text }}). If empty, the entire payload is evaluated."
    },
    "format": {
      "type": "string",
      "enum": [
        "json",
        "csv",
        "xml",
        "yaml"
      ],
      "default": "json",
      "title": "Format"
    },
    "csv_options": {
      "type": "object",
      "properties": {
        "has_header": {
          "type": "boolean",
          "default": true
        },
        "delimiter": {
          "type": "string",
          "default": ","
        }
      }
    },
    "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": {
    "raw": {
      "type": "string",
      "description": "The raw string to parse."
    }
  },
  "required": [
    "raw"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "parsed": {
      "type": "any",
      "description": "The structured result (Object/Array)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Success",
    "is_default": true,
    "description": "Parsing successful."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Parsing failed (e.g. malformed JSON)."
  }
]
```
