What is the best way to transform a unicode string into JSON format?

Looking to transform the Unicode string below into a JSON Object.

var str = '{"method_title":"Bank. Transfer","instructions":"Account Name: Sriram Me Co.,Ltd.\r\n----------------------------------------------\r\n- Furnin Commercial Bank\r\nAccount: 111-111-111\r\n----------------------------------------------\r\n- LIKSA Bank\r\nAccount: 111-111-111r\n----------------------------------------------\r\n\r\nAfter you have made bank transfer, please kindly visit \"PAYMENT\" to submit your payment detail."}';

This was my approach:

var myEscapedJSONString = decodeURIComponent(str);
console.log(JSON.parse(myEscapedJSONString));

The error I encountered is:

Uncaught SyntaxError: Unexpected token in JSON at position 82

Answer №1

decodeURIComponent is not effective in this scenario.

In order to utilize JSON.parse, the data format must be precise.

Therefore, it is necessary to eliminate line breaks initially using something like .replace(/(\r\n|\n|\r)/gm,"").

The subsequent issue involves the appearance of double quotes around "PAYMENT", which can be addressed by replacing them with

.replace(/"PAYMENT"/g, 'PAYMENT');

const str = '{"method_title":"Bank. Transfer","instructions":"Account Name: Sriram Me Co.,Ltd.\r\n----------------------------------------------\r\n- Furnin Commercial Bank\r\nAccount: 111-111-111\r\n----------------------------------------------\r\n- LIKSA Bank\r\nAccount: 111-111-111r\n----------------------------------------------\r\n\r\nAfter you have made bank transfer, please kindly visit \"PAYMENT\" to submit your payment detail."}';

const cleaned = str
  .replace(/(\r\n|\n|\r)/gm, "")
  .replace(/"PAYMENT"/g, 'PAYMENT');

console.log(JSON.parse(cleaned));

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 easiest method to access and modify a small JSON file using JavaScript?

In my video game, I have a JavaScript array of objects that represent an arcade-style leader board. The JSON structure is as follows: [ {"initials" : "JOE", "score": 20250}, {"initials" : "ACE", "score": 10010}, {"initials" : "YUP", "score": 5 ...

Using Ajax to update multiple text field rows with unique values

I have a question regarding utilizing Ajax to update the second text field based on the input from the first text field. I am looking to create multiple rows using a for loop, with each row having its own set of values. HTML <form style="text-align:c ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...

Issues involving JavaScript and jQuery

As a beginner in the world of JS and jQuery, I have encountered a problem that I am seeking assistance with. I am trying to use a script to insert content into a page, but I am facing a roadblock that I can't seem to overcome. Here's the specific ...

Single Sign-On with Cognito and Amplify in combination with Angular

I may have encountered this question before, but I am unable to find a solution. We currently have three websites built on Angular 10: sso.mywebsite.com dev.mywebsite.com demo.mywebsite.com When a user visits either the dev or demo site, they click on ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

I'm having trouble getting $.getJSON to function properly

Has anyone encountered issues with the getJSON function in jQuery? function loadJSON(){ console.log("loading JSON") var jsonFile = themeURL+"/map.json" $.getJSON(jsonFile, function(data){ console.log("loaded JSON") $("#infobox").fadeOut(1000 ...

What is the process for triggering a sorted output from my MongoDB database by simply clicking a button?

I'm struggling with sorting my collection by rating in my code. I have this snippet where I'm sending my collection to index.ejs: router.get('/', (req, res) =>{ FILM .find().limit(6) .then(films => res.render(& ...

Using Paper Checkbox to Toggle the Visibility of a Div in Polymer

Having experience with Meteor, I typically used JQuery to toggle the display of a div along with paper-checkbox: HTML: <paper-checkbox name="remoteLocation" id="remote-chk" checked>Remote Location</paper-checkbox> <div id="autoUpdate" clas ...

Showcasing top performers via JavaScript tabs

I have two tabs on my webpage: "Overall Leaderboard" and "Weekly Leaderboard". Each tab displays a leaderboard with different scores. When I click on the "Overall Leaderboard" tab, it shows a leaderboard with specific scores. Now, my question is how can ...

Synchronize React Hooks OnchangeORSync React Hooks On

Currently, I am in the process of transitioning my app from using a class model to utilizing hooks. In my code, there is a dropdown list where the onChange method performs the following function: filter(event) { this.setState({ selectedFilter: ...

"Utilizing the power of Angular 6's JSON pipe

Looking for a well-structured formatted JSON, but all I get is confusion and this strange image: https://i.sstatic.net/6mvBu.png Does anyone have any insights on what might be causing the issue? HTML <span style="font-weight: 500;">Payload Data: ...

What is the best way to find the maximum and minimum values within a JSON object that is populated from user inputs using only JavaScript?

Here is a simple form that stores data at the following link: https://jsfiddle.net/andresmcio/vLp84acv/ var _newStudent = { "code": code, "names": names, "grade": grades, }; I'm struggling to retrieve the highest and lowe ...

Executing Selenium tests: utilizing the webdriver.wait function to repeatedly call a promise

Currently, I am using Selenium ChromeDriver, Node.js, and Mocha for testing purposes... I am facing a dilemma at the moment: The driver.wait function seamlessly integrates with until. I have a promise, which we'll refer to as promiseA. This pro ...

What is the best way to change a date written in the format 'xxth Mar XXXX' into 'DD/MM/YY' format?

Currently, I am working on a React project and facing an issue with the date output format. The date is being displayed in the format of xxth Mar XXXX, but I need it in DD/MM/YY format. For example, if the date is shown as 18th Mar 2021, I want it to be d ...

Error: When attempting to submit to MondoDB, a TypeError occurred stating that property '_id' cannot be created on the number '1'

After retrieving 25 new comments in JSON format from a subreddit, my code converts it to a string, removes special characters, and generates a dictionary to track word frequency. The challenge lies in deciding whether to treat each word as a separate entry ...

Access to the remote resource at https://localhost:8000/users/login has been blocked due to a Cross-Origin Request restriction imposed by the Same Origin Policy

Attempting to send a post message to the /users/signup endpoint results in the same error occurring repeatedly. Below is the code snippet from server.js: const https = require('https'); const fs = require('fs'); var path = require(&apos ...

How come it's so difficult for me to find a simple demonstration of v-for in action in Vue JS?

After searching for a simple "hello world" example of using v-for in Vue.js, I have spent an hour looking at various posts, like the one on Stack Overflow, but still no luck. This is my HTML: <ul> <li v-for="item in history"> ...

At initial glance on iOS, the login page remains hidden, but as I tilt the phone, the page fields slowly start to appear

Encountering a strange issue when accessing my application on iOS 11. Initially, the page fails to load completely with missing background and field labels. However, I am able to click on objects. Oddly enough, if I tilt my iPhone or zoom in, the page load ...

Exploring user inputs and displaying variables using JavaScript and HTML 4.01

I was testing some code and I'm facing an issue that I can't figure out: <HTML> <head> <title> Page 1 </title> <script> function myFunction() { var x=document.getElementById("myEmail") document.write(x) } </scr ...