I have a json in which I store a property with a link. I want to write this to a .txt file so I can copy the content and use it in a resource object which has a serverUrl variable that I want to inject using template literals. Before I can do that I need to change the string value of the JSON a bit so I can use the template literals.
The json object has the following format:
{
"products": [
{
"image": "http://test.test.com/images/imageName.jpg"
},
{
"image": "http://test.test.com/images/imageName2.jpg"
}
]
}
What I am trying to achieve is to change every image value to the following format for each product object:
`http://${serverUrl}/images/imagename`
I managed to replace the url using a simple string.replace() during the json creation, but I am struggling with the following steps:
- Change the double quotes to graves ("" => ``) and keep the url.
- Do it globaly, I don't want to extract the values, the object should be overwritten.
I've tried writing some regexes, but I can't seem to figure out how I can replace both the double quotes and keep the url in one regex. Is this the right way to go about this? Or should I try something completely different
Edit
My code so far
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);