Currently, I am developing a JavaScript script to achieve the following tasks:
- Retrieve and interpret data from a JSON file
- Access an HTML file that serves as a template
- 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}
]
}
]
}