首页 > 解决方案 > 将一个键的值插入 .json 文件中另一个键的值

问题描述

这是我的 json 文件

{
    "foo": "https://3a1821d0.ngrok.io/api/foo",
    "bar": "https://3a1821d0.ngrok.io/api/bar",
}

我想3a1821d0用 json 文件中的另一个键替换,例如

{
    "some_variable": 3a1821d0,
},
{
    "foo": "https://some_variable.ngrok.io/api/foo",
    "bar": "https://some_variable.ngrok.io/api/bar",
}

这可能吗?如果是,如何?

标签: javascriptjson

解决方案


我建议将要替换的出现<>或任何其他字符包装起来,以使替换不会与外观发生冲突。调用你的文件input.json,这将是它的内容:

{
    "some_variable": "3a1821d0",
    "foo": "https://<some_variable>.ngrok.io/api/foo",
    "bar": "https://<some_variable>.ngrok.io/api/bar"
}

假设您正在使用节点。这段代码应该可以完成这项工作。

const fs = require('fs');

let fileContent = fs.readFileSync('input.json', "utf-8");

let content = JSON.parse(fileContent);
const someVariable = content.some_variable;

// I'm adding null and 4 to keep the file beautified
let fileContentStr = JSON.stringify(content, null, 4);

// This line replaces all ocurrences of <some_variable> by "some_variable" content
fileContentStr = fileContentStr.split('<some_variable>').join(someVariable);

// Write file again
fs.writeFileSync('output.json', fileContentStr);

推荐阅读