我有一个 json,其中存储带有链接的属性。我想将其写入 .txt 文件,以便我可以复制内容并在资源对象中使用它,该资源对象具有我想使用 template literals 注入(inject)的 serverUrl 变量。 。在执行此操作之前,我需要稍微更改 JSON 的字符串值,以便可以使用模板文字。
json 对象具有以下格式:
{
"products": [
{
"image": "http://test.test.com/images/imageName.jpg"
},
{
"image": "http://test.test.com/images/imageName2.jpg"
}
]
}
我想要实现的目标是将每个产品对象的每个图像值更改为以下格式:
`http://${serverUrl}/images/imagename`
我在 json 创建过程中设法使用简单的 string.replace() 替换了 url,但我在执行以下步骤时遇到了困难:
- 将双引号更改为坟墓 (""=> ``) 并保留网址。
- 全局执行,我不想提取值,应该覆盖该对象。
我尝试编写一些正则表达式,但我似乎无法弄清楚如何替换双引号并将网址保留在一个正则表达式中。 这是解决这个问题的正确方法吗?或者我应该尝试一些完全不同的东西
编辑
到目前为止我的代码
let dataImport = [];
// Code to convert excel to JSON
// Contains the following line for the image property
case "image":
value = value.replace("https://test.test.com", "${serverUrl}");
rowData["image"] = value;
break;
// Convert object
let json = JSON.stringify(dataImport, null, 2);
fs.writeFileSync("data.txt", json);
最佳答案
var json = JSON.stringify({
"products": [
{
"image": "http://test.test.com/images/imageName.jpg"
},
{
"image": "http://test.test.com/images/imageName2.jpg"
}
]
}, null, ' ');
var domain = "test.test.com";
console.log(convertJsonUrls(json, domain));
/**
* Converts any strings containing urls for the specified domain into template-strings,
* and replaces the domain with '${serverUrl}'
*/
function convertJsonUrls(json, domain) {
var stringRE = /"((?:\\.|[^\\"])*)"/g;
var urlRE = new RegExp("^(https?://)" + escapeRegExp(domain) + "(/.*)$");
var template = json.replace(stringRE, function (raw, content) {
var urlMatch = urlRE.exec(content);
if (!urlMatch) return raw; // no change, keep double-quotes
return "`" + urlMatch[1] + "${serverUrl}" + urlMatch[2] + "`";
});
return template;
}
/**
* Escapes any RegExp special characters.
* Copied from https://stackoverflow.com/a/6969486/22364
*/
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
关于javascript - 将字符串中的双引号替换为坟墓,而不创建新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396302/