You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编辑Hjson文件时如何保留注释?修改Variants数组的解决方案

解决Hjson修改时保留注释的方案

直接用serde_hjson这类仅处理数据结构的库会丢失注释,因为它们只序列化/反序列化数据,不保留语法层面的注释和格式信息。要实现需求,可采用以下两种思路:

一、基于AST(抽象语法树)的解析修改

使用支持保留语法结构(包括注释、空格、换行)的Hjson解析库,通过操作AST节点修改内容,再序列化回原格式:

Python环境示例

先安装依赖:pip install hjson

import hjson
from hjson.ast import KeyValue, String

# 读取原始Hjson文件
with open("config.hjson", "r", encoding="utf-8") as f:
    content = f.read()

# 解析为带注释的AST结构
ast = hjson.loads(content, object_pairs_hook=hjson.ast.AST)

# 遍历AST找到Variants节点并添加元素
for node in ast:
    if isinstance(node, KeyValue) and node.key == "Variants":
        # 向数组添加新元素v4(根据实际元素类型选择对应AST节点)
        node.value.append(String("v4"))
        break

# 将修改后的AST写回文件,保留原注释和格式
with open("config.hjson", "w", encoding="utf-8") as f:
    f.write(hjson.dumps(ast, indent=2, ensure_ascii=False))

Node.js环境示例

先安装依赖:npm install hjson

const Hjson = require('hjson');
const fs = require('fs');

// 读取文件并保留格式信息
const rawContent = fs.readFileSync('config.hjson', 'utf8');
const config = Hjson.parse(rawContent, { keepWsc: true });

// 修改Variants数组
config.Variants.push('v4');

// 写回时保留原注释和格式
const updatedContent = Hjson.stringify(config, { keepWsc: true, space: 2 });
fs.writeFileSync('config.hjson', updatedContent, 'utf8');

二、轻量文本替换法(适合格式规整的场景)

如果Hjson文件中Variants数组的格式固定(比如单行书写、元素用逗号分隔),可直接用正则表达式定位修改,无需解析整个AST:

Python环境示例

import re

with open("config.hjson", "r+", encoding="utf-8") as f:
    content = f.read()
    # 正则匹配Variants数组,在末尾添加新元素
    updated_content = re.sub(
        r'(Variants:\s*\[[^\]]*)(\])',
        r'\1, v4\2',
        content
    )
    f.seek(0)
    f.write(updated_content)
    f.truncate()

注意:这种方法依赖Variants数组的格式稳定性,如果数组是多行书写或格式多变,正则需要调整,可靠性不如AST方案。

内容的提问来源于stack exchange,提问作者Evgeny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:55:14