Using template literals in JSON (discord.js)


Using template literals in JSON (discord.js)



I have this JSON object:



"question": "The question, asked by ${users[index]}, was: nn${questions[index]}."


"question": "The question, asked by ${users[index]}, was: nn${questions[index]}."



in a file called "config.json". In a separate file named "app.js", I have this line of code:



message.channel.send(config.question);


message.channel.send(config.question);



When the code runs, message.channel.send(config.question) outputs:


message.channel.send(config.question)



The question, asked by ${users[index]}, was:



${questions[index]}.



Is there any way to treat ${users[index]} and ${questions[index]} as template literals? Essentially I want the output to be something like this:


${users[index]}


${questions[index]}



The question, asked by Steve, was:



Hello world!.



(assuming users[index] == "Steve" and questions[index] == "Hello World!")


users[index] == "Steve"


questions[index] == "Hello World!"



I searched around for answers, but they all came to using additional Javascript or saying it's not possible. Why, then, if it's not possible, would this work?:



message.channel.send("The question, asked by ${users[index]}, was: nn${questions[index]}");
outputs:


message.channel.send("The question, asked by ${users[index]}, was: nn${questions[index]}");



The question, asked by Steve, was:



Hello world!.





No. JSON can only contain quoted strings, not template literals. Where would it get the interpolation values from anyway? You will need to use a proper template engine for this.
– Bergi
Nov 21 '17 at 6:17





2 Answers
2



To do string interpolation in JavaScript, you need to use backtick (`) for the string literal.



For example:


`The answer is ${myVar}!`



will interpolate myVar into your string.


myVar





Would that go into the JSON question object or into message.channel.send("`" + config.question + "`")?
– Andy Herbert
Nov 21 '17 at 5:36


question


message.channel.send("`" + config.question + "`")



This would work:


message.channel.send(eval('`'+config.question+'`'))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages