Converting a string to JSON by adding it to the DOM

Recently, I have been working on creating a quick mock function for a unit test. To ensure that my assertions are tested accurately, I need to include an HTML element on the page with stringified JSON content. The system under test manipulates the stringified JSON data, converts it back into regular JSON format, and re-inserts it.

While setting up my mock insertion into the DOM, I noticed a peculiar behavior where the stringified JSON is being treated as actual JSON instead of just a simple string.

Here's a snippet of the code I was working on:

var mockJson = JSON.stringify({
    name: "Foo",
    data: {}
});
var mockScript = document.createElement("script");
mockScript.id = "myElement";
mockScript.textContent = mockJson;
document.body.appendChild(mockScript);

Surprisingly, the above code works perfectly fine. Upon execution, the #myElementelement is appended to the DOM containing the stringified mock object.

However, an error is also thrown:

VM136:1 Uncaught SyntaxError: Unexpected token ':'

This error seems to be triggered specifically on the last line of the script. It was puzzling at first because there was no : in that particular line. Eventually, I realized that the stringified mockJson is being interpreted as JSON, causing this anomaly.

To delve deeper, I replaced the complex mock object with a simple string in my testing:

var mockJson = "foo";
var mockScript = document.createElement("script");
mockScript.id = "myElement";
mockScript.textContent = mockJson;
document.body.appendChild(mockScript);

Even with this change, the script performed as expected by displaying the string "foo" inside the script element in the DOM. However, an error emerged stating:

VM179:1 Uncaught ReferenceError: foo is not defined

Evidently, it was attempting to interpret foo as a variable despite its declaration as a string.

What could be causing this dual behavior? While successfully incorporating the string as intended, why is it still generating an error?

Fiddle example

    var mockJson = JSON.stringify({
        name: "Foo",
        data: {}
    });
    var mockScript = document.createElement("script");
    mockScript.id = "myElement";
    mockScript.textContent = mockJson;
    document.body.appendChild(mockScript);

Answer №1

Adding JSON to a script element may lead to unexpected behavior, as script elements are meant for JavaScript code, not JSON data.

While a string literal in a script element is valid JavaScript syntax, an object literal is not and can trigger errors.

To avoid issues, consider using a <pre> element instead of a <script> element when adding JSON data for automated tests.

If you must use a script element, setting a type attribute to indicate that it isn't JavaScript could be a workaround.

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

The installation of Semantic-UI through NPM hit a snag because of an issue with

I am in the process of setting up the necessary dependencies for my react app. I have listed all the required packages in my package.json file and initiated the installation with npm install. However, the output is showing an error: > <a href="/cdn- ...

Designing a personalized confirmation pop-up following the submission of an AJAX form

I am currently utilizing the AJAX JQuery validation plugin to submit a form. Below is a snippet of the code: $(document).ready(function(){ $("#myform").validate({ debug: false, rules: { fname: {required: true}, sname: {required: t ...

Error message encountered while using Node.JS IPFS: TypeError occurs when attempting to send a message, as it cannot read undefined properties related to 'publish

Every time I attempt to send a message over the IPFS network, I encounter the following error message: TypeError: Cannot read properties of undefined (reading 'publish'). This error crops up at line number node.pubsub.publish(topic, msg, (err) = ...

Utilizing C# for parsing a JSON reply

I am currently facing an issue with deserializing the JSON data shown below: { "related": [ { "titulo": "pt cruiser models" }, { "titulo": "pt 19" }, ... // More related items ] } H ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

Processing large amounts of data in Excel using Node.js

I am struggling with efficiently writing large data to an excel file while optimizing server memory usage. When I extract data from a SQL database to the server, which comprises more than 1 million rows, it consumes a significant amount of time and memory. ...

Tips for confirming that one of three checkboxes has been selected in AngularJS

Here is the code snippet for checkboxes: <input name="chkbx1" type="checkbox" ng-model="LoanReferData.Prop1" ng-class="Submitted?'ng-dirty':''" required>Prop 1</input> <input name="chkbx2" type="checkbox" ng ...

Manipulating images live with options for scaling, resizing, and cropping

I am currently developing a content management system that allows users to upload images and attach them to different sections of the pages. My goal is to find a user-friendly, preferably jQuery-based plugin for resizing images before they are cropped. A ...

The initial value is always NaN when parsing JSON

Check out my fiddle here I am encountering an issue with my JSON code where the first ID is always showing up as 0 and I can't seem to identify the cause of this problem. Here is the iteration loop: for (var i = 0; i < myFirstJSON.length; i++) ...

How to set a referer in C# using EO.WebBrowser

Looking for a solution to modify the referer in EO.WebBrowser. I know you can change the User-Agent using: webView1.CustomUserAgent, but it seems there isn't a direct method for changing the referrer. Are there any alternative approaches to achieve th ...

Unsuccessful conversion of JSON data to HTML using json2html in Python

I have been experimenting with converting JSON data to HTML using json2html. The JSON data structure I am working with is as follows: json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username" ...

Saving the KineticJS JSON data in a mySQL database, and subsequently retrieving it on a different page to refresh the canvas display

Trying to resolve a dilemma I'm facing... I've crafted a small T-Shirt-Shop using KineticJS. The stage is stored in a JSON string with toJSON() and saved in a mySQL database. However, when attempting to retrieve the string from the database on ...

Ways to prevent a React component from re-rendering when a sibling component re-renders

Recently, I've delved into the world of React and Redux but hit a snag. I have a button that triggers an API call to fetch information about cars. The process goes like this: Upon button click, it dispatches the function getCars(), which then trigger ...

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

Scroll to the next list group item and align the content in the center when viewing on mobile devices using React

1) I need help with implementing auto scrolling to the next item in a list group. Specifically, when a user answers the first question, it should automatically scroll to the second question (using React). Additionally, upon submitting the form, it should s ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

What methods is Facebook using to manage their onbeforeunload confirmation dialog?

While using Facebook on the latest Chrome browser on my Mac, I observed an interesting behavior. When I began typing in a comment box and then clicked on another link or pressed the back button, a confirmation window popped up asking if I wanted to leave: ...

Is it possible to create custom input fields using the Stripes Payment-Element?

I recently integrated Stripe into my next.js application to facilitate one-time payments. Following the standard tutorial for Stripe Elements, I created a PaymentIntent on initial render: useEffect(() => { // Create PaymentIntent as soon as the ...

Buttons aligned vertically alongside an input text field

I am trying to align two buttons vertically under an input text box with the middle aligned. This is what I have done so far: jQuery(document).ready(function($) { // Implementing bootstrap minus and plus plugin // Reference: http://jsfiddle.net/lael ...

The navigation in Flutter's local JSON list view is experiencing technical difficulties

When working with Flutter, I encountered an issue retrieving JSON data locally and displaying it on a single screen. To resolve this, follow these steps: Create an asset folder in your project root directory Place your JSON file into the asset folder ...