Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS use variables in JSON file strings

I use a JSON file for common phrases so I don't have to type them and maybe in the future they can be translated. So for example in my main code I want to say You don't have the permission to use ${command_name}. This works perfectly fine hardcoded into my .js file but ultimately I want this to be in a JSON file, which does not allow any variables to be inserted.

Does anyone know a solution to my problem?

EDIT: Thanks for the suggestions. I guess string.replace would be my best option here. Wish there was some built in feature that'd convert variables in a JSON string to variables declared in that JS file.

like image 252
Galaxy Avatar asked Sep 21 '26 13:09

Galaxy


1 Answers

You cannot treat template string literals in JSON files like in Javascript "code". You said it yourself. But: You could use a template engine for this - or just simple String.replace().

Example for a template engine: https://github.com/janl/mustache.js

With Mustache (as an example) your code will look like this

var trans = {
  command_name: "dump"
};

var output = Mustache.render("You don't have the permission to use {{command_name}}", trans);

With simple String.replace():

var str = "You don't have the permission to use %command_name%";

console.log(str.replace('%command_name%', 'dump'));
like image 121
madflow Avatar answered Sep 23 '26 03:09

madflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!