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

如何使用string.replace()方法替换嵌套对象占位符为values.js中的值?

问题说明

需要将collection.js中的占位符__fruit_type__、__clothing_type__、__fitness_equipment__、__meditation_app__替换为values.js中对应的取值,要求通过string.replace()方法实现。


相关文件代码片段

collection.js

{"collection" : [
    {
      "fruit": "__fruit_type__",
      "clothings":{
        "item": "__clothing_type__"
      }
    }, 
    {
      "fitness": "__fitness_equipment__",
      "mindfulness": "app called __meditation_app__"
    }
]
}

(注:原代码中__clothing_type__}多了一个冗余右大括号,已修正以保证JSON格式合法)

values.js

{
    "clothing_type": "winter",
    "fruit_type": "apple",
    "fitness_equipment": "treadmill",
    "meditation_app": "calm"
}

replace.js(初始版本)

const fs = require("fs").promises;

async function dataReader(filePath, data) {
  const result = await fs.readFile(filePath);
  try {
    return JSON.parse(result);
  } catch (e) {
    console.error(e);
  }
}
//read values
async () => {
  const value = await dataReader("./values.json");
  const clothing_type = value.clothing_type;
  const fruit_type = value.fruit_type;
  const fitness_equipment = value.fitness_equipment;
  const meditation_app = value.meditation_app;

  //read collection.json
  const data = await jsonReader("./collections.json");

  //replace tokens in `collection.js` with `values.js`
};

解决方案

修改replace.js,通过读取原始字符串、批量替换占位符、验证格式后写入文件的方式实现需求,完整代码如下:

const fs = require("fs").promises;

// 读取文件并返回原始字符串(不解析JSON)
async function readFileAsString(filePath) {
  try {
    return await fs.readFile(filePath, "utf8");
  } catch (e) {
    console.error("读取文件失败:", e);
    throw e;
  }
}

// 读取并解析JSON文件
async function readJsonFile(filePath) {
  try {
    const content = await fs.readFile(filePath, "utf8");
    return JSON.parse(content);
  } catch (e) {
    console.error("解析JSON失败:", e);
    throw e;
  }
}

// 执行占位符替换逻辑
async function replacePlaceholders() {
  try {
    // 读取values配置
    const values = await readJsonFile("./values.json");
    // 读取collection的原始字符串
    let collectionStr = await readFileAsString("./collection.json");

    // 遍历values,批量替换对应占位符
    for (const key in values) {
      const placeholder = `__${key}__`;
      // 用正则全局替换所有匹配的占位符
      collectionStr = collectionStr.replace(new RegExp(placeholder, "g"), values[key]);
    }

    // 验证替换后的JSON格式合法性
    const updatedCollection = JSON.parse(collectionStr);
    // 将格式化后的内容写回文件
    await fs.writeFile("./collection.json", JSON.stringify(updatedCollection, null, 2));

    console.log("占位符替换完成!");
  } catch (e) {
    console.error("替换过程出错:", e);
  }
}

// 启动替换流程
replacePlaceholders();

关键细节

  • 使用带g标志的正则表达式,确保所有匹配的占位符都被替换(避免仅替换第一个)
  • 先读取原始字符串再替换,避免JSON解析后丢失占位符的字符串结构
  • 替换后重新解析JSON验证格式,保证输出内容合法
  • 写入文件时用JSON.stringify的格式化参数,让输出的JSON更易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:50:25