写在前面
Coze工作流的某些组件,比如HTTP组件会将原本的object响应输出为string,或者某些插件只支持array的变量接入,所以需要用到代码组件将string清洗为object或array。
string2object
from
{
"input": "{\"success\":true,\"url\":\"https://ocr-viewer.breadkim.com/outputs/20250515_105949_04c13c90/ocr_viewer.html\"}\n"
}
to
{
"output": {
"url": "https://ocr-viewer.breadkim.com/outputs/20250515_105949_04c13c90/ocr_viewer.html",
"success": true
}
}
code
async function main({ params }: Args): Promise<Output> {
// 将输入字符串转换为对象
let parsedObject;
try {
// 尝试解析JSON字符串
parsedObject = JSON.parse(params.input);
// 构建输出对象 - 注意这里直接将解析后的对象分配给 output 属性
return {
output: parsedObject
};
} catch (error) {
// 如果解析失败,返回错误信息
return {
output: {
"error": `解析JSON失败: ${error.message}`,
"input": params.input
}
};
}
}
string2array
from
{
"input": "https://p9-bot-workflow-sign.byteimg.com/tos-cn-i-mdko3gqilj/874523bdd18b4688a30db83b37f906e7.png~tplv-mdko3gqilj-image.png?rk3s=c8fe7ad5&x-expires=1778407213&x-signature=dJuQB7%2FXZbAcQqBu6%2Bt9kZhagy0%3D"
}
to
{
"output": [
"https://p9-bot-workflow-sign.byteimg.com/tos-cn-i-mdko3gqilj/874523bdd18b4688a30db83b37f906e7.png~tplv-mdko3gqilj-image.png?rk3s=c8fe7ad5&x-expires=1778407213&x-signature=dJuQB7%2FXZbAcQqBu6%2Bt9kZhagy0%3D"
]
}
code
async function main({ params }: Args): Promise<Output> {
// 构建输出对象
const ret = {
output: [params.input],
};
return ret;
}
array2string(firstElement)
from
{
"input":[
"https://s.coze.cn/t/r4GgZ5lpzdQ/"
]
}
to
{
"output": "https://s.coze.cn/t/r4GgZ5lpzdQ/"
}
code
async function main({ params }: Args): Promise<Output> {
// 直接把传进来的参数当作数组
const inputArray: any[] = params.input;
let firstElement: any;
// 如果真的是数组且长度大于 0,就取第一个;否则返回 null(或按需改成其他默认值)
if (Array.isArray(inputArray) && inputArray.length > 0) {
firstElement = inputArray[0];
} else {
firstElement = null;
}
return {
output: firstElement
};
}
array2string(firstvalidValue)
from
{
"input":[
"",
"https://s.coze.cn/t/r4GgZ5lpzdQ/"
]
}
to
{
"output": "https://s.coze.cn/t/r4GgZ5lpzdQ/"
}
code
async function main({ params }: Args): Promise<Output> {
// 获取输入数组
const arr: string[] = params.input;
// 找到第一个非空字符串(即有效值)
const validValue = arr.find(item => typeof item === 'string' && item.trim() !== '') || '';
// 构建返回对象,将有效值放到 output 字段中
const ret: { output: string } = {
output: validValue
};
return ret;
}
评论