Every time I use JSON.stringify on an object, I end up with a wild and wacky string returned

Whenever I attempt to transmit an object containing an array of objects from my express route to the client, I receive an [Object object]. Then, when I try to convert it into a string using JSON.stringify, I end up with a convoluted string along with a console message.

var messages = "<%=(JSON.stringify(messages))%>"
console.log(messages) 

This is what gets displayed in the console...

{&#34;messages&#34;:[{&#34;content&#34;:&#34;cool mane&#34;,&#34;creator&#34;:&#34;joe&#34;},{&#34;content&#34;:&#34;test 4&#34;,&#34;creator&#34;:&#34;joe&#34;},{&#34;content&#34;:&#34; ewgdqf&#34;,&#34;creator&#34;:&#34;joe&#34;},

I expect to be able to iterate through the data by accessing messages[0].content, but instead, I am presented with a confusing string that hinders any further manipulation...

Any attempts at looping through the string only results in each character being printed individually.

Answer №1

By utilizing the EJS syntax <%= ... %>, any output is encoded or escaped automatically. This explains why the quotations marks ("") in the JSON data are shown as &#34;. As referenced in this particular response, one way to avoid escaping is by opting for <%- ... %>.

Furthermore, there is no necessity to enclose the generated content within a string literal. In fact, this practice should be avoided as it may lead to issues with nested quotes. Allow the output to be directly inserted into the JavaScript code like so:

var data = <%-JSON.stringify(data)%>;

Answer №2

Consider replacing the following code snippet:

var data = "<%=(JSON.stringify(data))%>"
console.log(data) 

With this alternative approach:

var data = JSON.stringify("<%=data%>");
console.log(data) 

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

Error: Syntax error - V token not recognized

Although this question is quite common, I am interested in understanding the theoretical reason behind it. I am attempting to send two encrypted values to my service. Javascript var encryptedlogin = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(Ema ...

What is the best way to conceal specific series in a HighCharts legend?

In the chart, I currently have 4 series. At the moment, only 2 of them are visible while the other 2 are hidden when the chart first loads. As the user zooms in on the chart, the visibility of the series changes dynamically. I need help figuring out how ...

Is it possible to implement Google authentication with Passport.js session in a Next.js application?

I am currently in the process of selecting a technology stack and I'm curious if it's possible to integrate express passport.js session google authentication with next.js? ...

Having trouble accessing Vuex's getter property within a computed property

Can you help me troubleshoot an issue? When I call a getter inside a computed property, it is giving me the following error message: TS2339: Property 'dictionary' does not exist on type 'CreateComponentPublicInstance{}, {}, {}, {}, {}, Com ...

Strive to discover the ideal solution for capturing a screenshot of an OpenLayers map using html2canvas. Currently, the map elements are losing their CSS classes and images are not

Seeking advice on the best solution for working with html2canvas and css. I'm trying to take a screenshot of a map that includes various elements, but after capturing the image, all the css classes are lost and the images are not rendered properly. S ...

customizing highcharts title within a popup window

Is there a way to dynamically set the title of a Highcharts chart from an element? Check out my code snippet below: $(function () { var chart; $('#second-chart').highcharts({ chart: { type: 'bar' }, subtitle: { ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

What are some creative ways to utilize postMessage instead of relying on nextTick or setTimeout with a zero millisecond delay?

I just came across a theory that postMessage in Google Chrome is similar to nextTick. This idea somewhat confused me because I was under the impression that postMessage was primarily used for communication between web workers. Experimenting with expressio ...

The input value remains a string even after it has been converted to a float

I can't figure out where I'm going wrong. I'm attempting a simple task: getting user input, converting it to a float, and performing a calculation with that value. However, all I keep getting is NaN. Here's the input (I normally replac ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

I have a task of extracting information from a live Google map and generating a static Google map using API V3

I am working on a project that involves allowing users to create maps using Google Maps and then save the image. My current workaround uses both the Google Maps API V3 and the Static Maps API. The user can interact with the dynamic Google map by scrolling ...

What is the best way to transfer data from my browser to the backend of my application?

I am currently working on developing a basic weather application using Express and Node.js. To accomplish this, I need to automatically retrieve the latitude and longitude of the user. While I understand how to achieve this through HTML5 Geolocation in t ...

Change all instances of the subtraction symbol to parentheses using jQuery

--html-- <table> <tr> <th>a</th> <th>b<th> </tr> <tbody class = "tabledata"> <tr>a</tr> <tr>b</tr> </tbody> </table> --jquery-- $('.tabledata').empty(); for ( ...

Having trouble with the alias in commander.js not functioning as desired when using the "--help" option

Currently, I am facing a strange issue while working on my project with commander.js. The problem arises when assigning an alias for a command. I looked at some examples mentioned in the reference: Commander.JS Example I decided to create a git-like comma ...

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...

Changing a Unique JSON Structure into a VB.NET Object

I have a JSON object that is structured as follows. { "Errors":{ "err1":[ //* Array of err1 objects ], "err2":[ //* Array of err2 objects ] } } This object is used to report errors identified in a request to a PHP page. My goal i ...

Trying to understand the strange behavior of HTML parsing with jQuery in Javascript and Firefox

I have been working on a script to parse an HTML page using jQuery. The script runs smoothly in Chrome, IE, and Safari, but I'm facing some unexpected behavior while testing it in Firefox (version 36.0.1). Here's the code snippet: $.ajax({ u ...

What is the proper method for setting initial values for scope upon loading the view using AngularJS and ngInit?

For the last few weeks, I've been immersing myself in AngularJS, studying large-scale applications to gain insights into real-world development practices. One common pattern I observed is the use of ng-init="init()" when loading a view - essentially c ...

When modifying v-model directly in a Vue instance, the Vuetify component on the screen may not update its displayed value

Within my Vue component example (utilizing Vue 2 and Vuetify 1), I have implemented an input field for user data entry. However, I am looking to programmatically alter the input field's data to a specific value. For instance, in this scenario, I aim ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...