When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals:

        var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.`

This functions correctly as shown below:

https://i.sstatic.net/YaKco.png

However, when dealing with JSON data that contains a template literal wrapped string as a value, it doesn't behave the same way.

var templateDataObject = [
            {"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}`"}}
        ]

https://i.sstatic.net/crGO8.png

How can one insert variable values using template literals when the template is sourced from JSON data? Is there a correct approach to tackle this issue?

Check out the full code snippet below:

<html>
    <head>
        <title>JS Select Exercise</title>
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b5bebeb5b2b5b1e3aab7e3bee0fee0fee4abb6c777">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <hr/>
            <div class="row">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <select class="form-control" id="select_demo" onchange=onKidChange(this)></select>
                            <br/>
                            <h3 id="agevalue"></h3>
                            <br/>
                            <h3 id="statement"></h3>
                            <button class="btn btn-sm btn-primary" onclick=printStatement()>Print Statement</button>
                            <br/><br/>
                            <button class="btn btn-sm btn-info" onclick=printAnotherStatement()>Print Another Statement</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
    <script>
        var jsonDataObject = [
            {"model": "A", "identifier": 1, "fields": {"name": "Stan", "age": "12"}},
            {"model": "B", "identifier": 2, "fields": {"name": "Brett", "age": "14"}}
        ]
        
        var filteredJSONExample = jsonDataObject[0]['fields']
        
        var templateDataObject = [
            {"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExampl...

// Error: text too long for AI to rewrite 

Your help on this matter is highly appreciated!

Answer №1

When you create:

"`Greetings, my name is ${name}`"

It's a simple traditional string with content:

`Greetings, my name is ${name}`

No fancy formatting, no special functionality. It's just a basic string with some variable information.

JSON & template literals don't really mix well because JSON properties need to be plain strings, not templates. So typically, you should keep them separate when working with data.

If you need to dynamically insert values into standard strings, one approach is to use placeholders and then replace them with the desired content. Here's an example:

const message = "Greetings, my name is $name$!";

message.replaceAll("$name$", "Sarah");
// Greetings, my name is Sarah!

The Chrome extensions API follows this same method for internationalization. You can check out the structure of the underlying JSON in the documentation for more details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the precise location of the div element

I am seeking to determine the precise positions of a div based on its class name. In the screenshot provided, my script for finding the div's position is highlighted in yellow, while the div I am targeting is highlighted in red at the bottom. Currentl ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Transform the JSON data using jQuery into a specific structure

My current project involves creating a pie chart using flot, and I am receiving JSON data from the server in the following format: [ {"transactions": 7, "products__name": "mark"}, {"transactions": 12, "products__name": "vicky"}, {"transactions": 3 ...

What is the best way to include text in an editor access notification email?

I've developed a script to assign editors to a spreadsheet, but I'm looking to personalize the emails sent to them. The screenshot below illustrates the step where I can input a message for the email recipients who have been granted access. f ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...

unable to transmit form data through ajax using a JSON object

I've been attempting to send JSON data via AJAX in a Jersey API, but I'm encountering difficulties with sending the data. Below is my code: Javascript Code var jsonObj = createDataObj(); $.ajax({ type : "POST", ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Using Strapi and Next.js to retrieve user information

After searching for similar questions with no luck, I'm reaching out for help. Building an authentication system using Strapi and Next.js, I'm faced with a task that seems simple but eludes me. The main question is: How can the client retrieve u ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

Strategies for Mitigating Duplicate Requests in AngularJs with just one click

I am facing an issue with my AngularJS application where clicking on a link triggers the API call twice. I'm not sure why this happens and how to fix it. My service: SomethingService function getData() { return apiSettings.getApiInformation().t ...

Exploring the depths of nested image objects using the map method in ReactJS

I successfully mapped through and destructured this object, but I'm struggling to access the image within the same map. I believe I may need to map through it separately, but I'm uncertain. Here is the object: { "attributes": { ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

Seamless integration of Applitools with WebdriverIO

Seeking assistance to integrate Applitools with my WebdriverIO project. Find the specifications below: Node Version: v12.18.2 NPM Version: 6.14.5 WebdriverIO Version: 6.3.6 The service in my wdio file is configured as follows: services: ['selenium-s ...

Top pick for building drag-and-drop web applications: the ultimate JavaScript library

Up to this point, I've relied on jQuery UI's draggables and droppables for my projects. However, I recently came across ExtJS and other libraries that caught my interest. I am aiming to create a professional-grade plugin. Can anyone suggest the b ...

Spinning Global Lighting and Bouncing in three.js

I am trying to create a 3D object that automatically rotates around the Y axis while still allowing users to scale and custom rotate the object with their mouse. This is what I have so far: import * as THREE from 'three'; import { GLTFLoader } f ...

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

Revising the $.parseJSON Function in jQuery 1.9.1 to Match jQuery 1.8.3's Implementation

With the latest version of jQuery, 1.9.0, there have been changes in the implementation of $.parseJSON which is causing some issues for us. We relied on how earlier versions of jQuery handled null and empty strings, where it would return a null value inste ...

Guide to attaching a page content button to a fixed header

I am currently developing a webpage with a sticky header, and I want to include an animated button that moves onto the header when scrolled past. You can check out my code snippet here: https://jsfiddle.net/ykL50pjf/ The specific ID for the button is #t ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...