What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code:

res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) ))

//No errors occur here and the object is successfully stringified //The 'user' object is returned in MongoDB's result https://i.stack.imgur.com/5QYJw.png

The resulting JSON string appears as follows:

{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0N31dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.y...

The 'uid' mentioned above is simply a MongoDB primary key represented as a string, with the other two base 64 strings functioning as JWT tokens.

Upon reaching the browser, the JSON string is parsed using the following method:

JSON.parse(`<userdata>`)
//Please note the usage of filex.replace("<userdata>", JSON.stringify...) on the server side

For your reference, my MongoDB Document looks like this:

After executing JSON.parse on the provided JSON string, the final JavaScript code appears as such:

JSON.parse(`{"name":"Rishavolva","uid":"5f3ce234fd83024334050872","profile":{"pic":{"small_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ4fSx7ImRiX25hbWUiOiJpZnJkYjAwMiIsInRhYmxlIjoiRklMRSIsImlkIjo0OH1dLCJ1aWRfd2hpdGVsaXN0IjoiKiIsImlhdCI6MTU5ODE2MzMzNX0.9NkGnEumn4JW8IN0KFgxgN_6_4wN8qOgezNTyzz9osY","big_link":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXBsaWNhcyI6MiwidXJpcyI6W3siZGJfbmFtZSI6ImlmcmRiMDAxIiwidGFibGUiOiJGSUxFIiwiaWQiOjQ3fSx7ImRiX25hbWUiOiJpZnJkYjA...

An error is encountered during this process:

Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 1 column 702 of the JSON data

The issue seems to be related to the presence of '\n' at position 702 within the JSON string.

The question arises - can '\n' be classified as a control character?

How can this be resolved effectively? Is this problem stemming from the MongoDB result?

Answer №1

\n represents a new line in text. When dealing with JSON, these characters need to be escaped when used within strings.

If not properly escaped, an error may occur:

JSON.parse(`{"hello":"world\n"}`)

To avoid this error, ensure proper escaping like so:

   JSON.parse(`{"hello":"world\\n"}`)

To handle this issue, consider using functions such as replace to escape your content before converting it to JSON format. More information can be found here: How to escape a JSON string containing newline characters using JavaScript?

Answer №2

After conducting some experiments, I have come up with a solution. The key is to use JSON.stringify() two times,

For example,

html_text.replace('/*<whatever>*/', JSON.stringify( JSON.stringify(the_object) ) )

If we assume that html_text contains the following line

<script>
const object_inbrowser = JSON.parse(/*<whatever>*/)
// you don't need to add quotes, `JSON.stringify` on the server will handle that for you
</script>

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 could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Saving Information from an HTML Form Input?

I am currently working on a form that collects information about employees including their name, age, position, and details. When the "Add Record" button is pressed, this information should be added to a designated div. Although I have set up the Object C ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

After I refresh the state in my React form, the data within my child components starts exhibiting odd behavior

My weather app in React seems to be facing a strange issue. When I select a new city and reload the data, my child components display a mix of old and new data multiple times before finally showing the correct information. What could be causing this proble ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

Search a database for a specific set of ObjectID using Mongoose

I'm currently developing an API using node.js, express, and mongoose. As I am still new to mongosse, I have been exploring different approaches to achieve what I need. In my database, I have two collections: users and expenses. Here's an exampl ...

React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded? I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set withou ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

What methods can I use to prevent a JavaScript array from getting filled during page loading?

Looking for assistance to populate an array using JQuery with option values from multiple select elements. I need the array to reset and fill with new options each time a select element is used. Strangely, despite my efforts, the array appears pre-filled w ...

data storage using sessionstorage for session management

Currently, I am managing sessions in my MEAN app by utilizing AngularJS to store user data in the browser's sessionStorage. The process consists of: User logs in through the front-end User is fetched from the back-end (node) Returned data is saved t ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Transforming JSON data into string format

Looking for a way to convert the JSON below into a fully string-quoted JSON format using Python. Is there a method in the python "json" module that can help with this, or is there a simpler parsing code available? Original data: data = '[{"id":334," ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Implementing jQuery and JavaScript validation for email addresses and usernames

Are the online validations being used incorrectly or is there a serious issue with them? I came across an example of a site using jQuery validation, but when I entered "44" for a name and ##@yahoo.com for an email address, no warning appeared. I haven&apo ...

access the first JSON key in Swift

When I send a HTTP GET request, the response can either be: {"events":"Event Goes Here"} or {"service":"Service goes here"} Currently, I am creating two separate HTTP Get functions to handle the responses. For example: if let results: NSArray = json ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

Tips for enabling resize functionality on individual components one at a time

Check out my Codepen link for the resizable event While using Jquery UI resizable, everything is functioning correctly. However, I am now looking to have the resizable event activate one block at a time. When another block is clicked, the resizable event ...