javascript - 将一个键的值插入 .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",
}
这可能吗?如果是,如何?
解决方案
我建议将要替换的出现<>
或任何其他字符包装起来,以使替换不会与外观发生冲突。调用你的文件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);
推荐阅读
- php - 打印xml中的每个标签
- javascript - 根据 localStorage 项目值加载样式表
- unix - sed: -e 表达式 #1, char 40: 未终止的 `s' 命令
- javascript - 用css将元素中心放在左上角,以便将“变换”引用到元素的中心
- java - Hibernate不在H2中创建表
- rest - Jenkins REST API:创建新的作业视图
- sql - 从 SQL LIKE 查询中排除标点符号
- ios - iOS - 检查 [CGPoint] 做一条直线
- unity3d - 如何子弹不统一跟随对象
- android - 构建 android 内核时出现错误“function 'nop'”