How to represent a JavaScript string with a new line character using JSON.stringify without the escape sequence displaying

I am currently working on converting a string to JSON in JavaScript and then sending the converted string to an HTML textarea element. The original string from the backend looks like this:

"customBar_query": "select\\n\\neq.Name,\\nAVG(Payload) as [Average Payload]\\n\\nfrom tbl.Cycles as c\\nleft join dim.Equipment as eq on eq.Id = c.Truck_Id\\nwhere c.Timestamp_Loading >= DATEADD(day,-365,GETDATE())\\n\\nGROUP BY eq.Name\\n\\nORDER BY [Average Payload] DESC"

The "\\n" sequence is meant to represent a newline character.

Here is how I'm parsing the string:

var newChartData = JSON.parse(data);

The resulting JavaScript string looks like this:

customBar_query: "select\n\neq.Name,\nAVG(Payload) as [Average Payload]\n\nfrom tbl.Cycles as c\nleft join dim.Equipment as eq on eq.Id = c.Truck_Id\nwhere c.Timestamp_Loading >= DATEADD(day,-365,GETDATE())\n\nGROUP BY eq.Name\n\nORDER BY [Average Payload] DESC"

At first glance, everything seems fine. However, when inspecting the object in Developer Tools, the expected "enter" symbol denoting a new line is not visible. Similarly, assigning this value to a textarea using jQuery's .val() displays the text with "\n" strings instead of actual line breaks, like so:

select\n\neq.Name,\nAVG(Payload) as [Average Payload]\n\nfrom tbl.Cycles as c\nleft join dim.Equipment as eq on eq.Id = c.Truck_Id\nwhere c.Timestamp_Loading >= DATEADD(day,-365,GETDATE())\n\nGROUP BY eq.Name\n\nORDER BY [Average Payload] DESC

I am unable to comprehend why this is happening. This behavior is unexpected and I would appreciate any guidance or suggestions!

UPDATE

For reference, below is a snippet from Chrome Developer Tools showing that the string \n is not being displayed as an "enter" symbol.

https://i.sstatic.net/CXALf.jpg

Answer №1

These values are in string format and do not contain any newlines yet. We anticipate that newlines will be represented as \n within a string, and simply as a newline character in the log.

Displayed here is the data containing newlines within a textarea.

const jsonstring = `{"customBar_query": "select\\n\\neq.Name,\\nAVG(Payload) as [Average Payload]\\n\\nfrom tbl.Cycles as c\\nleft join dim.Equipment as eq on eq.Id = c.Truck_Id\\nwhere c.Timestamp_Loading >= DATEADD(day,-365,GETDATE())\\n\\nGROUP BY eq.Name\\n\\nORDER BY [Average Payload] DESC"}` const obj = JSON.parse(jsonstring); const txtArea = document.getElementById("x"); const pre = document.getElementById("output") 
Object.values(obj).forEach(val => { txtArea.value += val; output.textContent += val; }) 
console.log(pre.innerHTML)
textarea {
height: 400px;
width: 400px;
}
<textarea id="x"></textarea> <pre id="output"></pre>

Answer №2

After some investigation, I discovered the issue. It appears that '\n' is the correct syntax for JSON parsing in Javascript. The problem arose when I had two different data sources pulling from the same function. One was injected through Django ({{dashboardJson|safe}}) into the HTML file, while the other came through Javascript Ajax.

The use of the '|safe' function in Django caused interference with the \n values, leading me to send \\n to ensure the JSON validity. However, the Javascript Ajax only needed \n, not \\n, resulting in invalid string rendering.

It's puzzling why Django altered the strings, as they appeared fine at first glance. Nonetheless, something definitely changed during the process.

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

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

Managing operations in Swift 2.0

I am currently working with Swift 2.0 on IOS 9.2.1 using Xcode 7.2. As I am learning Swift 2.0, I have developed a routine that involves creating a NSURL Session to retrieve JSON data and parsing it successfully. Everything is working as expected... Howe ...

Retrieve the keys from the initial object within an array of objects

I am looking to extract a list of unique keys from an array of objects. arr =[ {id: 1, desc: "", name: "", objectives: Array(3), …}, {id: 2, desc: "", name: "", objectives: Array(3), …}, {id: 3, desc: "", name: "", objectives: Array(3), …}, ...

What are some effective troubleshooting methods for resolving issues with chrome.storage.sync?

My Chrome extension is a simple tool that utilizes the chrome.storage API to keep track of tasks in a organized list. Whenever there is an update to the task list, the array is saved to chrome.storage.sync. I have both of my laptops configured with the Ch ...

The npm outdated command reveals that there are some modules missing in the current version

In my package.json file, I have specified babelify version 7.3.0 in the devDependencies section like this: "devDependencies": { ..., "babelify": "7.3.0", ... } Everything seems to be working fine and the dependency is downloaded from npm. However, ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Synchronous JavaScript function with live update

I'm currently working on a function that performs a lengthy task, and I'm looking to implement a feature that notifies the caller of the progress. My end goal is to update the user interface with the current progress status. Here's an examp ...

Why does my array become empty once it exits the useEffect scope?

const [allJobs, setAllJobs] = useState([]); useEffect(() => { axios.get('http://localhost:3002/api/jobs') .then(res => setAllJobs(res.data)); allJobs.map((job, i) => { if (job.language.toLowerCas ...

AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview However, I seem to be overlooking something as it's not working in my implementation. HT ...

Tips for creating mocks/stubs for vue-i18n?

I have recently made the switch from Jest to Vitest as my unit testing library for my Vue 3 application. Currently, I am facing an issue while trying to write a unit test for a component that utilizes the vue-i18n library for text translation. When attemp ...

Organizing array entries by key and key values with jq

Here is a sample json data: { "hits": [ { "country": "PT", "level": "H2", "id": "id1" }, { "country": "CZ", "level&quo ...

display data from a hashmap in a React component

Struggling with extracting data from a hashmap retrieved from an API for my React application. Here's a snippet of the data: [ [ "d243dc7-6fe8-151b-4ca8-1be528f2b36", "[\"Jonny\",70]" ], ...

Deliberately "locking" a JavaScript variable with a immediately-invoked function expression

While browsing through a blog post here that discusses creating a web scraper using node.js, I stumbled upon an intriguing piece of javascript that has left me somewhat perplexed. This particular snippet of code seems like something I could implement in my ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Is it possible to synchronize functions in node.js with postgresql?

I’m facing some challenges in managing asynchronous functions. Here is the code snippet that's causing the issue: var query = client.query("select * from usuario"); query.on('row', function(user) { var queryInterest = client. ...

What is the best way to connect an image using Flask and javascript?

I'm attempting to insert an image into a card using JavaScript, structured like this: console.log(account_name); document.getElementById("list_of_datasets").innerHTML += ` <div class="col-lg-4 d-flex align-items-stret ...

Add together the values retrieved from various AJAX calls

I'm attempting to calculate the total value of the data returned by multiple ajax requests. However, I am facing an issue where the total is always showing as 0 because the calculation is happening before the ajax requests are completed. var totalRev ...

The overlay background is being obscured by surrounding elements

Hey there! I'm experimenting with some basic coding and ran into an issue with an overlay. Here's the site link: Sorry for the strange language. :-) If you click on the button with the tiny icon, you'll notice that the overlay form isn&apos ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...