ComfyUI icon indicating copy to clipboard operation
ComfyUI copied to clipboard

How to edit node id to string not a number for save workflow api

Open nicehero opened this issue 1 year ago • 5 comments

Your question

Current save workflow api json. The node is is like this { "1": { .... The node id Is a number. I can manually edit the json file,change it to a string,and edit the context for the string id. But it is too complex,and maybe some error. Can I edit the node id in comfyui web page?

Logs

No response

Other

No response

nicehero avatar Aug 11 '24 14:08 nicehero

Can you share a sample workflow.json and steps to reproduce?

huchenlei avatar Aug 11 '24 15:08 huchenlei

Can you share a sample workflow.json and steps to reproduce?

Save the api workflow. Like this. Now I change the node 5 to a string number1.But I want this work can do in webui.

{
  "5": {
    "inputs": {
      "int": 0
    },
    "class_type": "Int Literal",
    "_meta": {
      "title": "Int Literal"
    }
  },
  "6": {
    "inputs": {
      "input": [
        "5",
        0
      ],
      "output": ""
    },
    "class_type": "Display Int (rgthree)",
    "_meta": {
      "title": "Display Int (rgthree)"
    }
  }
}

Now I change the node 5 to a string number1.

{
  "number1": {
    "inputs": {
      "int": 0
    },
    "class_type": "Int Literal",
    "_meta": {
      "title": "Int Literal"
    }
  },
  "6": {
    "inputs": {
      "input": [
        "number1",
        0
      ],
      "output": ""
    },
    "class_type": "Display Int (rgthree)",
    "_meta": {
      "title": "Display Int (rgthree)"
    }
  }
}

But I want this work can do in webui.

nicehero avatar Aug 11 '24 15:08 nicehero

Do you want a feature to assign a custom unique ID(like "number1") instead of a Node Number that generates by ComfyUI?

bigcat88 avatar Aug 11 '24 16:08 bigcat88

Do you want a feature to assign a custom unique ID(like "number1") instead of a Node Number that generates by ComfyUI?

Yes,I need it.

nicehero avatar Aug 11 '24 16:08 nicehero

Do you want a feature to assign a custom unique ID(like "number1") instead of a Node Number that generates by ComfyUI?

Yes,I need it.

open develpment mode, you can save format

dyfqpl1 avatar Aug 20 '24 10:08 dyfqpl1

I code a python script to do that:

import json
import os
import sys

def validate_json(data: dict):
    """
    对加载的 JSON 进行基础结构校验。
    如果校验不通过,可以直接 print 提示并退出程序,或者 raise Exception。
    """

    # 1. 必须包含 last_node_id
    if "last_node_id" not in data:
        print("错误:JSON 文件中缺少 'last_node_id' 字段")
        sys.exit(1)  # 退出程序

    # 2. 必须包含 nodes,且为列表
    if "nodes" not in data:
        print("错误:JSON 文件中缺少 'nodes' 字段")
        sys.exit(1)
    if not isinstance(data["nodes"], list):
        print("错误:'nodes' 字段不是列表类型")
        sys.exit(1)
    
    # 3. 每个节点必须有 id
    for i, node in enumerate(data["nodes"]):
        if not isinstance(node, dict):
            print(f"错误:第 {i} 个节点不是字典类型:{node}")
            sys.exit(1)
        if "id" not in node:
            print(f"错误:第 {i} 个节点缺少 'id' 字段:{node}")
            sys.exit(1)

    # 4. 必须包含 links,且为列表
    if "links" not in data:
        print("错误:JSON 文件中缺少 'links' 字段")
        sys.exit(1)
    if not isinstance(data["links"], list):
        print("错误:'links' 字段不是列表类型")
        sys.exit(1)

    # 5. 每条 link 应该是一个包含 6 个元素的列表 [link_id, from_id, from_port, to_id, to_port, "label"]
    for i, link in enumerate(data["links"]):
        if not isinstance(link, list):
            print(f"错误:第 {i} 条链接不是列表类型:{link}")
            sys.exit(1)
        if len(link) != 6:
            print(f"错误:第 {i} 条链接的元素数量不是 6:{link}")
            sys.exit(1)

    print("JSON 文件结构校验通过!")

def main():
    # 固定的 JSON 文件名
    json_filename = "color-animate-2-people.json"
    
    # 判断文件是否存在
    if not os.path.exists(json_filename):
        print(f"错误:未找到 JSON 文件 {json_filename}")
        return

    # 读取文件到内存
    with open(json_filename, "r", encoding="utf-8") as f:
        data = json.load(f)

    # 先做一次结构校验
    validate_json(data)

    # 如果通过校验,进入循环询问用户,直到用户输入 stop
    while True:
        # 1. 获取用户输入
        to_replace_id = input("请输入要替换的 ID (toReplaceID), 或输入 stop 退出: ")
        if to_replace_id.strip().lower() == "stop":
            print("已停止批量替换操作。")
            break

        replace_id = input("请输入新的 ID (replaceID): ")
        if replace_id.strip().lower() == "stop":
            print("已停止批量替换操作。")
            break

        # 2. 执行替换逻辑
        replaced_count = 0

        # 2.1 替换 last_node_id
        if str(data.get("last_node_id")) == to_replace_id:
            data["last_node_id"] = replace_id
            replaced_count += 1

        # 2.2 替换 nodes 中的 id
        for node in data.get("nodes", []):
            if str(node["id"]) == to_replace_id:
                node["id"] = replace_id
                replaced_count += 1

        # 2.3 替换 links 中的节点 id
        # 每个元素形如 [link_id, from_id, from_port, to_id, to_port, "xxx"]
        for link in data.get("links", []):
            # link[1] 是 from_node_id,link[3] 是 to_node_id
            if str(link[1]) == to_replace_id:
                link[1] = replace_id
                replaced_count += 1
            if str(link[3]) == to_replace_id:
                link[3] = replace_id
                replaced_count += 1

        # 3. 写回到文件(覆盖保存)
        with open(json_filename, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

        print(f"替换完成:共替换了 {replaced_count} 处,结果已保存到源文件 {json_filename}")
        print("=============================================")

if __name__ == "__main__":
    main()

XuWeinan123 avatar Jan 10 '25 12:01 XuWeinan123

This issue is being marked stale because it has not had any activity for 30 days. Reply below within 7 days if your issue still isn't solved, and it will be left open. Otherwise, the issue will be closed automatically.

github-actions[bot] avatar Mar 04 '25 11:03 github-actions[bot]