Having trouble converting data back to JSON format after using JSON.parse in an ejs file with node and express

I'm retrieving data from an external API on my server, then attempting to pass that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file by parsing it with JSON.parse(data). However, I am encountering issues where I either receive something like [Object object] or a string filled with strange characters. I have even tried using the replace method, but it still doesn't seem to resolve the problem.

Here is an example of what I have on the server side:


router.get("/api", (req, res) => {

  const info = {
    place: "London",
    country: "UK",
    temp: "16",
    weather: "Cloudy",
  };
  res.render("weathery", { user: JSON.stringify(info) });

}

And here is what I have on the ejs file side:


<script>
  var data = "<%= user %>";
  const newData = data;

  console.log(newData);
</script>

When printing without using JSON.parse, this is the result:

{"place":"London","country":"UK","temp":"16","weather":"Cloudy"}

I attempted replacing special characters like #, &, ;, and 34, but it didn't work. Additionally, this could cause problems if the data includes the number 34 in some cases.

Every time I try to parse the data, I receive the following error message: "Uncaught SyntaxError: Unexpected token & in JSON at position 1"

If you can provide assistance, I would greatly appreciate it. Have a wonderful day! :)

Answer №1

Transform this

var text = "<%= user %>"

Into this:

var text = `<%- user %>`

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

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

An unexpected character was found during the parsing of the value: S. Path '', line 0, position 0

Despite the abundance of posts on this topic, I struggled to find a solution that addressed my specific issue. I want to clarify that I have already verified that the encoding is correct. Additionally, the Exception sometimes occurs and sometimes doesn&apo ...

Error message: validator is not defined when integrating jquery.validate with jquery.uploadfile package

Currently, I am facing an issue while attempting to incorporate both jquery.validate and jquery.uploadfile on the same page. The error message I'm receiving is: TypeError: validator is undefined if ( validator.settings.rules ) { Interestingly, if ...

Troubleshooting: Vue.js file upload encountering OPTIONS 404 error

In my express app, I have configured CORS and most of the routes are working fine. However, I'm facing an issue with a specific component used for uploading images: <input type="file" class="form-control" @change="imageChanged"> <div @clic ...

Modify the `div` content based on the selected items from the bootstrap dropdown menu

My navigation bar is built using Bootstrap and contains multiple drop-down items. Now I have another div with the class of col-md-3. Within this div, I would like to display the items of the dropdown menu when hovered over. Currently, hovering over a dro ...

Traversing through nested JSON using a jQuery each loop

My goal is to implement a simple JSON file that can be used to populate multiple select boxes. The starting point is a static select box with the following options: <select> <option value="first">This is the first</option> <option val ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make qu ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Tips for assigning data from an AJAX response to a variable

Using jQuery and the code provided, there seems to be an issue with variable scope when some_condition is false. The error "items is not defined" indicates this problem. The goal is to set the result variable to the AJAX response data in order to use it o ...

Steps for removing routing in Angular 2 after setting the folder as a dependency for another project

In my testing Angular project (referred to as project1), I am developing components and utilizing routing for organizational and aesthetic purposes. There is another Angular project (referred to as project2) which includes the component project-project1 i ...

Best practices for assigning values to model field in EXT JS are as follows:

I'm facing an issue with a certain model structure: Ext.define('my.workspace.Area', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'string'}, {n ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Error message: "PHP encountered an issue with an undefined array key while attempting to

Hello everyone! I'm new to this community and eager to learn. Currently, I am diving into PHP and working on a program to upload files. I stumbled upon a tutorial with some code that seems a bit confusing due to my limited understanding of PHP termino ...

Retrieving a single value from the response entity JSON data

I am in need of connecting to a rest service in order to retrieve the user id using a token. List<Object> providers = new ArrayList<>(); providers.add(new JacksonJaxbJsonProvider()); client = WebClient.create(properties.getProperty(URL), prov ...

Python App Engine: Parsing a JSON file in gitkit

RELEVANT CODE First Try: directory = os.path.dirname (__file__) path = os.path.join (directory, 'json', 'gitkit-server-config.json') gitkit_instance = gitkitclient.GitkitClient.FromConfigFile (path) Second Try: directory = os.p ...

Issues with pop-up windows on YII2 gridview

I am currently developing a web application using the Yii2 framework for my company to efficiently manage their storage. I have incorporated various plugins from kartik-v to enhance the functionality of the application. However, I am facing an issue with i ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

What is the simplest method to create a scroller for engaging narratives?

I am in the process of creating a static but responsive storytelling website using HTML. My objective is to create an effect similar to this: https://i.stack.imgur.com/zIEpU.gif The idea is to have text on the left and a *.jpg image fixed on the right. As ...

Tips for maintaining the InteractionCollector's presence even after a Discord.js bot reboot

One of the tasks my AI assistant handles is processing proposals submitted through Google Forms and transferring them to a designated channel where individuals can cast their votes by selecting either Yes or No using the corresponding MessageButton. Once ...