Swapping out content in an HTML document using JSON data

Currently, I am developing a JavaScript script to achieve the following tasks:

  1. Retrieve and interpret data from a JSON file
  2. Access an HTML file that serves as a template
  3. Substitute elements in the HTML file with corresponding elements from the JSON file

However, I have encountered a challenge where only the first element obj.verb is being replaced. I would greatly appreciate assistance in identifying any errors in my syntax or overall approach. Please see the code snippet below along with a preview of the contents within the referenced JSON file.

fs.readFile("./tasks/example.json", 'utf8', function(err, jsonObjectForHIT){

// parse json file and store it in variable obj
var obj = JSON.parse(jsonObjectForHIT)

// read the template file 
fs.readFile("./tasks/StageOneQuestionTemplate1.html", function(err, addedXML){
// replace values from template with values from json object and assign to variable finalXML
var finalXML = String(addedXML).replace(/VerbGoesHere/g, obj.verb);
var finalXML = String(addedXML).replace(/RoleOne/g, obj.roles[0]);
var finalXML = String(addedXML).replace(/RoleTwo/g, obj.roles[1]);
var finalXML = String(addedXML).replace("RoleThree", obj.roles[2])
}

Sample JSON file mentioned above:

{
"verb": "tenir",
"roles": [
            {"name": "with whom"},
            {"name": "thing held"},
            {"name": "conductor"}
        ],
"srcLanguageSentence": { "text": "Burmah said it had n't held any discussions with SHV and that `` no deal of any nature is in contemplation .",
                        "verb": {"text": "held", "sense": "HOLD, conduct", "beginOffset": 24, "endOffset": 28},
                        "roles": [
                                    {"name": "with whom", "text": "with SHV", "beginOffset": 45, "endOffset": 53},
                                    {"name": "thing held", "text": "any discussions", "beginOffset": 29, "endOffset": 44},
                                    {"name": "conductor", "text": "it", "beginOffset": 13, "endOffset": 15}
                                ]
                       },
"tgtLanguageSentences": [
                            { 
                                "text": "Je tiens également à mentionner la récente Conférence , tenue au Canada , sur les enfants touchés par la guerre.",
                                "verb": {"text": "tenue", "beginOffset": 57, "endOffset": 62},
                                "roles": [
                                    {"name": "thing held", "text": "la récente Conférence , , sur les enfants touchés par la guerre", "beginOffset": 33, "endOffset": 112},
                                    {"name": "location information", "text": "au Canada", "beginOffset": 63, "endOffset": 72}
                                ]
                            }
                       ]

}

Answer №1

obj.roles[0] represents an object {"name":"with whom"}. It is not possible to replace a string with an object. Make sure to reference the property "name" within the object.

obj.roles[0].name

Another issue is that var finalXML receives a new value on each line. Instead of replacing the value, you should be adding to it.

 var finalXML = String(addedXML).replace(/VerbGoesHere/g,obj.verb)
 .replace(/RoleOne/g,obj.roles[0].name)
 .replace(/RoleTwo/g,obj.roles[1].name)
 .replace("RoleThree",obj.roles[2].name);

Answer №2

Perhaps the correct syntax is obj.roles[].name rather than obj.roles[]

let newXML = String(updatedXML).replace(/RoleOne/g,obj.roles[0].name);
let newXML = String(updatedXML).replace(/RoleTwo/g, obj.roles[1].name);
let newXML = String(addedXML).replace("RoleThree", obj.roles[2].name);

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

Utilizing the foreach loop in PHP to display JSON data from the CoinMarket API

I am having trouble printing JSON data in a PHP foreach loop. I have tried multiple methods but nothing seems to work. The data is coming from the CoinMarket API and I am currently using the following code to print it, however, I am unable to access each v ...

Retrieve JSON details for various games including their properties

I am currently working on a project that involves accessing Casino Games and their properties from a JSON object to display them on a website. Here is my progress so far: var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?for ...

What strategies can be implemented to avoid using .stop() in specific scenarios?

Currently, I am working on a jQuery animation where clicking on a tile should display its information by hiding all other tiles and showing its details. While I have implemented .stop() to prevent queuing issues, I encountered a problem with the transition ...

Mistakes in serializing arrays for javascript in an ajax request

I am trying to send an array of JavaScript objects in an Ajax call. This is how I create my array: var itemsToEdit = []; $(".editedItem[value='true']").closest("tr").each(function() { var itemToEdit = { id: $(this).find(".i ...

When you select a checkbox, it successfully toggles the first time, but fails to do so the second time [S

When it comes to issuing invoices, here's the process I follow: First, I make sure to select all invoices on the current page by clicking on the checkbox. Then I proceed to hit the issue button and give my approval for them to be issued. Once the cu ...

What's the reason behind beforeunload not triggering?

I've gone through numerous similar posts, but I'm struggling to figure out what's not quite right with this code snippet: $(window).on("beforeunload", function () { debugger handleBeforeUnload(); return false; }); function handl ...

Add values to each entry in a subarray

let b = []; this.state.sidejobs.forEach((user) => { console.log(user); if (!b.hasOwnProperty(user.jobworker)) b[user.jobworker] = 0; b[user.jobworker] += user.duration; }); I have a query regarding splitting and adding durations in entries where ...

Tips for accessing data directly from a database rather than relying on JSON for every request

After watching a tutorial on YouTube, I was inspired to create a way to deliver articles from a WordPress blog using the JSON API. You can check out the GITHUB link for more details. The tutorial provided a good example, but it only showed data from the d ...

Improving the quality of shadows in Three.js

I'm looking to create realistic shadows in my scene using a DirectionalLight to simulate sunlight. However, I'm struggling with the shadow quality settings - toggling between on/off, Low, Normal, and High: Setting parameters a and b within these ...

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Performing aggregation in MongoDB with nested subdocuments

I have a specific document structure as shown below: { "_id": "some_uuid", "inv": { "food01": "id01", "food02": "id02", "food03": "id03" }, " ...

DIV will not show the Real Ajax Uploader interface

I've hit a roadblock. I recently purchased the Real Ajax Uploader Source codes and it functions perfectly on its own. However, when I attempt to display it in a DIV, things go haywire - only showing one DIV with non-functional JS code inside. There ar ...

Is it possible to verify the authenticity of published npm packages by utilizing hashes/checksums?

As I prepare to release an npm package on behalf of my organization, let's call it Organization A, I want our clients to have a means of verifying that the package they are using was indeed released by us. One method to accomplish this is by computing ...

Modifying CSS content attribute in real-time

A colleague of mine has rented a webshop from a company. They have the option to select different templates and are also able to customize the CSS and add Javascript snippets. They reached out to me for help with making some modifications, but there's ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...

EmberJS: Learning how to create a record with a belongsTo relationship

My issue involves using Posts and Comments to explain my problem. In my post_controller, I am trying to create a new record for a comment related to the current post. What is the recommended way to achieve this in Ember? The relationship between Post and ...

Easily update the title of a webpage in the browser's history using JavaScript

Is it feasible to use JavaScript to modify the title of a page in the browser history even after the page has finished loading? This functionality should work consistently across different browsers, including those that do not support the HTML5 History API ...

Guide to shutting down Bootstrap 5 modal using React

Incorporating bootstrap 5 with react in my project without installation, I am utilizing CDN links to integrate bootstrap elements into the DOM. The challenge arises when attempting to close the bootstrap modal after data is updated. Despite trying to uti ...

The Node script remains active even after all setTimeout functions have completed

I have a script that updates the passwords of all existing Firebase Authentication users we use for testing purposes to reset them to a "clean" state. var admin = require('firebase-admin'); // Input args var jsonKey = process.argv[2]; var proje ...

Trouble initiating Nodejs project on Heroku platform

Attempting to deploy a nodejs application on heroku.com has been a challenge. Although the code was successfully pushed to heroku master, accessing the application resulted in an error message. https://i.sstatic.net/r5yQE.jpg Upon checking the logs, the ...