Deciphering JSON strings using JavaScript

Here is a string that I am trying to parse using Json:

{\"description\": \"PSY - Gangnam Style (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) \\n\\u25b6 NOW available on iTunes: http:\\\/\\\/Smarturl.it\\\/psygangnam\\n\\u25b6 Official PSY Online Store US \\u0026 International : http:\\\/\\\/psy.shop.bravadousa.com\\\/\\n\\u25b6 About PSY from YG Ent.: http:\\\/\\\/smarturl.it\\\/YGfamilyAboutPSY\\n\\u25b6 PSY's Products on eBay: http:\\\/\\\/stores.ebay.com\\\/ygentertainment\\n\\u25b6 YG-eShop: http:\\\/\\\/www.ygeshop.com\\n \\n===============================\\nPSY CONCERT \\\"HAPPENING\\\"\\n2013.4.13. SAT 6:30PM\\nTHE SEOUL WORLD CUP STADIUM\\nYouTube LIVE@ http:\\\/\\\/www.youtube.com\\\/officialpsy\\nTickets: http:\\\/\\\/smarturl.it\\\/PsyHappeningKor\\nEnglish Booking: http:\\\/\\\/smarturl.it\\\/PsyHappeningEng\\n===============================\\n\\nFor More Information @\\nhttp:\\\/\\\/www.facebook.com\\\/officialpsy\\nhttp:\\\/\\\/twitter.com\\\/psy_oppa\\nhttp:\\\/\\\/twitter.com\\\/ygent_official\\nhttp:\\\/\\\/me2day.net\\\/psyfive\\nhttp:\\\/\\\/www.psypark.com\\nApp Store: http:\\\/\\\/goo.gl\\\/l9TU6\\nGoogle Play: http:\\\/\\\/goo.gl\\\/UiEn1\\n\\n\\u00a9 YG Entertainment Inc. All rights reserved.\"}

My attempt to convert \\" to " with this code:

tmp = tmp.replace(/\\"/gi, '"'); 

Resulted in the following snippet:

{"description": "PSY - Gangnam Style (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) \\n\\u25b6 NOW available on iTunes: http:\\\/\\\/Smarturl.it\\\/psygangnam\\n\\u25b6 Official PSY Online Store US \\u0026 International : http:\\\/\\\/psy.shop.bravadousa.com\\\/\\n\\u25b6 About PSY from YG Ent.: http:\\\/\\\/smarturl.it\\\/YGfamilyAboutPSY\\n\\u25b6 PSY's Products on eBay: http:\\\/\\\/stores.ebay.com\\\/ygentertainment\\n\\u25b6 YG-eShop: http:\\\/\\\/www.ygeshop.com\\n \\n===============================\\nPSY CONCERT \\"HAPPENING\\"\\n2013.4.13. SAT 6:30PM\\nTHE SEOUL WORLD CUP STADIUM\\nYouTube LIVE@ http:\\\/\\\/www.youtube.com\\\/officialpsy\\nTickets: http:\\\/\\\/smarturl.it\\\/PsyHappeningKor\\nEnglish Booking: http:\\\/\\\/smarturl.it\\\/PsyHappeningEng\\n===============================
\\nFor More Information @\\nhttp:\\\/\\\/www.facebook.com\\\/officialpsy\\nhttp:\\\/\\\/twitter.com\\\/psy_oppa\\nhttp:\\\/\\\/twitter.com\\\/ygent_official\\nhttp:\\\/\\\/me2day.net\\\/psyfive\\nhttp:\\\/\\\/www.psypark.com\\nApp Store: http:\\\/\\\/goo.gl\\\/l9TU6\\nGoogle Play: http:\\\/\\\/goo.gl\\\/UiEn1\\n\\n\\u00a9 YG Entertainment Inc. All rights reserved."}

However, a snippet still contains

PSY CONCERT \\"HAPPENING\\"\\n2013.4.13. SAT 6:30PM
. Is there a decoding method that can be used to make the string valid for json object parsing?

Answer №1

It appears that your string is double-escaped but lacks its outer delimiters.

let str = '{\\"description\\": \\"PSY - Gangnam Style (\\\\uac15\\\\ub0a8\\\\uc2a4\\\\ud0c0\\\\uc77c) … .\\"}';
let jsonStr = JSON.parse('"'+str+'"'),
    obj = JSON.parse(jsonStr);

Answer №2

One approach, although not ideal, is to evaluate your string before parsing it into JSON:

eval("temp = \"" + temp + "\";");
var tempJSON = JSON.parse(temp);

However, it's important to note that evaluating an unknown string can be risky. It may be safer to explore decoding functions that achieve the same result.

Why does this method work?

Your string appears to resemble a code snippet with escape backslashes used to represent quotes and backslashes. For example, when defining a string as var str = "He said \"ok\"";, the output will be He said "ok". In contrast, if the string contains escape characters within, it would be defined like this:

var str = "He said \\\"ok\\\"";

This would produce a string like:

He said \"ok\"

Within the eval function, everything is interpreted as code. So, executing:

eval("str = \"" + str + "\";");

would effectively run the following line of code:

str = "He said \"ok\"";

resulting in the desired unescaped string:

He said "ok"

Answer №3

While not as sophisticated as the method proposed by basilikum and perhaps not as accurate as the two-step parsing technique recommended by Bergi and Jonathan Lonowsky, an alternative approach could involve utilizing a JavaScript negative lookbehind equivalent. Consider using the following code snippet:

str.replace(/\\+"/gi, function(s){return (s.length % 2) ? s : s.slice(0,-2) + '"';})

It is worth noting that this method offers a more secure solution compared to directly evaluating the string.

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

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...

Generate a Flask template using data retrieved from an Ajax request

Struggling with a perplexing issue. I'm utilizing Ajax to send data from my Javascript to a Flask server route for processing, intending to then display the processed data in a new template. The transmission of data appears to be smooth from Javascrip ...

Transform Java JSONArrays into Map Objects Effortlessly

I am currently working on a Java class that has the purpose of converting JSON into a Map by using a specific key. Below, you can find the desired method format and steps: public Map<String, Map<String, String>> convert(String jsonBody, String ...

Insert a page break after content for desktop browsers

Is it possible to control the display of sections on different screen sizes? I have a page that looks good on 15" laptops, but larger resolutions cause the next section to appear on the first screen. Is there a way to show the next section only on th ...

Stopping HTTP redirection in Angular 2

Attempting to simulate user login using Angular2 Http. Let's describe the situation below. There is a PHP application where users can log in through http://sample.com/login.php URL (a form exists with username and password input, users must fill in ...

A streamlined method to verify the presence of a username or email address in MongoDB before registering

I'm currently running a NodeJS server with ExpressJS to manage my /register route. As part of the registration process, I need to confirm that both the user's username and email are unique before allowing them to create an account in the users co ...

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

Unable to edit the current value of an input component in ReactJS

I need to implement a search feature for a list of items using ReactJS. You can view the project on JSBIN. The issue I am facing is that when I input 'mi' in the search box to filter by ID, the filtration works correctly but the input value does ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

Tips for achieving comma-separated user input via ngModel and appending it to an array

I am working on an email template that includes a cc option. I want users to be able to add email addresses with commas separating them and then push them to an array called $scope.notifyCtrl.cc. How can I accomplish this using AngularJS 1.5 and above? mai ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...

I'm a beginner when it comes to working with MongoDB and I'm looking to insert a new field into a specific document. Can anyone advise me on how to accomplish this using Node

As an illustration, consider a document structured as follows: {_id:1, name:"John" } If a new field is added, the document will be updated to: {_id:1, name:"John", last_name:"doe" } ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Incorporate a prefix into the URL of Angular development servers

When our application is in production, it will not be served from the root. Instead, it will be served from something like https://ourdomain.com/ourapp. This setup is causing problems with image URLs. To work around this issue, I am trying to serve the ap ...

Working with PHP results in JSON outputs containing arrays

I need help processing the JSON result: ["13:00:00","14:00:00"] in my mobile application using Java language. The JSON may vary in length, with a maximum of 8 items or 8 hours. I send a PHP request from my application, triggering a query to run and return ...

What causes the TypeError: 0 is not a function error when using Array.from as a callback for Array.flatMap?

An issue arises when using Array.from as a callback with Array.flatMap, resulting in the error message: "TypeError: 0 is not a function" const x = ["12"].flatMap(Array.from) console.log(x) However, when used as a regular function, Array.from operates n ...

Error encountered during installation of Grunt Bower

As an AngularJS beginner, I am trying to start a node server with npm start on a project cloned from Bitbucket. However, I encountered an error while doing this. I attempted a few solutions such as unblocking port 22 in the firewall settings and running t ...

Using JavaScript to fetch HTML and apply CSS dynamically

Is there a way to retrieve all HTML within a div along with the corresponding CSS? A majority of the CSS is defined in classes within an external stylesheet. document.getElementById("mydiv") Currently, using the above code only fetches the HTML with inli ...