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

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

Making changes to a specific JSON value within a JSON Array in SQL

I am looking to make changes to an existing JSON value within a JSON array. I have the ability to add a new JSON object to the array using JSON_MODIFY. For example, if my JSON looks like this: [{"id":"101","name":"John"}, {"id":"102","name":"peter"}] How ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Leverage the power of puppeteer alongside webpack

Struggling to make puppeteer work with webpack? Despite adding it to package.json and configuring webpack.dev, the 'launch' function still throws errors. Here's what I've tried: Installed dependency in package.json: npm i puppeteer In ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

Firebug version 2.0.1 has been triggered to break on previous breakpoints

Despite adding and removing breakpoints, Firebug continues to stop at the old breakpoints upon refreshing the page. I attempted solutions such as resetting all Firebug options and deleting the breakpoints.json file, but they have not resolved the issue. ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

What is the best way to halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the ...

What are some strategies for handling data after it has been retrieved using Axios?

In my current project, I am working with MySQL database and fetching data using Axios and a useEffect hook. Once the data is retrieved, I pass it to a component as a prop. Here's how: const Component = () => { //Database URL const urlProxy = &q ...

Exploring the Intersection of Tcl Lists and Json

My introduction to the json package in Tcl has led me to the challenge of converting a list of lists into json format. While the code below provides the desired results, I am curious if there may be a simpler method or potential issues with the current i ...

Error will be thrown if the initialDueDate parameter is deemed invalid in Javascript

Can someone help me improve the calculateNextDueDate function which takes an initialDueDate and an interval to return the next due date? I want to add argument validation to this function. Any suggestions would be greatly appreciated. Thank you! const I ...

Angular2's change detection mechanism does not behave as anticipated after receiving a message from a Worker

Within my angular2 application, I encountered a rather intriguing scenario which I will simplify here. This is AppComponnet export class AppComponent { tabs: any = []; viewModes = [ { label: "List View"}, { label: "Tree View" }, ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

Stop the multer photo upload in Node/Express if validation for other fields fails

One issue I am facing is with multer as middleware before the editing user function. The problem is that multer uploads the photo regardless of any other conditions, so I'm looking for a way to possibly cancel the upload if, for example, the email is ...

"Why does the React useState array start off empty when the app loads, but then gets filled when I make edits to the code

I'm facing a challenging task of creating a React card grid with a filter. The data is fetched from an API I developed on MySQL AWS. Each card has a .tags property in JSON format, containing an array of tags associated with it. In App.jsx, I wrote Jav ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...