Dealing with errors when attempting to parse invalid input using JSON.parse()

While working on a solution to manage cookies in JS, I encountered an issue. The cookies I am dealing with can have content in JSON format, like so:

var cookieContents = '{"type":"cookie","isLie":true}';

... or they could simply be plain strings:

var cookieContents = 'The cookie is a lie';

When trying to parse the cookie using JSON.parse(cookieContents), I realized that JSON.parse() cannot handle plain strings and throws a fatal error.

So, my question is: What is the most widely accepted approach to handle this situation?

I attempted to use a try/catch block:

var cookie1 = '{"type":"cookie","isLie":true}';
var cookie2 = 'The cookie is a lie';

function parseCookieString(str){
    var output;

    try{
        output = JSON.parse(str);
    } catch(e){
        output = str;
    }

    console.log(output);
}

parseCookieString(cookie1); // outputs object
parseCookieString(cookie2); // outputs string

You can view the code in action here: http://jsfiddle.net/fmpeyton/7w60cesp/

Although this method works well, it feels somewhat makeshift. I typically do not handle fatal errors in JavaScript. Is it common practice to address these errors more elegantly in such scenarios?

Answer №1

Implementing a try catch block is logical, but if JSON.parse throws an error due to reasons unrelated to your output variable, it could result in unintended content within the variable.

This predicament presents an intriguing challenge. One potential solution would involve checking for the existence of { and } in the string:

function validateCookieString(str){
    var output;

    if (!!str.match(/^{.+}$/)) {
      output = JSON.parse(str);
    } else {
      output = str;
    }

    console.log(output);
}

validateCookieString(cookie1); // outputs object
validateCookieString(cookie2); // outputs 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

In a React function component, the return statement is present but it returns nothing

Just starting out with Js and React, trying to navigate my way through this framework. I'm encountering an issue in this component where it's indicating that either nothing is being returned or the return statement is missing, even though I have ...

What is causing the issue with the code `exports = { z: function() {} };` not functioning as intended?

Script A exports = { z: function() { console.log('aZ'); } }; Script Main require('./a').z(); // error Have you ever wondered why require('./a') ends up returning an empty object? ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

Placing an element on the page starting from the bottom and moving it towards the

Is there a way to display items on a page from bottom to top, similar to how messages are shown in a chat? Here's an example: .chart div { font: 10px sans-serif; background-color: steelblue; padding: 3px; margin: 1px; color: white; disp ...

What is the rationale behind requiring a semicolon specifically for IE11 in this function?

Currently, I am tackling some vuejs code to ensure compatibility with IE 11. Struggling with a persistent expected semicolon error in this particular function: chemicalFilters: function (chemical) { var max = 0; var min = 100; for (var ...

Check every URL path in an array against a regular expression pattern using preg_match_all

Here is a regular expression example: \["([^_]+)"\] \[ - Matches a "[" character " - Matches a """ character [^_] - Groups multiple tokens together and creates a capture group for extracting a ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

This article will discuss how to send back an HTML response and include a cookie using Cloud

I'm trying to achieve the dual task of setting a 'Set-Cookie' response header and modifying an HTML response by adjusting CSS. Essentially, I want to combine these two actions into one (or consolidate my two IF statements): const country = ...

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

Unable to eliminate the string "C:fakepath" using JavaScript's replace function and regular expressions

I've been struggling for quite some time with this issue. Let me share a snippet of the code that's causing trouble: jQuery(':file').change(function() { var path = jQuery(this).val(); var filename = path.replace(/C:\\ ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

Next-auth custom authentication provider with unique backend

I am currently experiencing an issue with sessions while using auth authentication. My next-auth version is 4.0.0-beta.4 (also tried beta.7 with the same results). My backend utilizes a custom JWT token system that returns an object containing an access t ...

Is the function failing to return a value?

I'm facing an issue with a certain piece of code that doesn't seem to be working as expected. Essentially, I have an array containing the accepted file types for a specific component. The code is designed to iterate over this array and check if t ...

span element causing border-spacing problem

Is there a way to adjust the spacing between these borders? I've tried using border-spacing but it doesn't seem to be working. https://i.sstatic.net/ZY05g.png {{#each spacing}} <span class='space'> {{business}} ({{Count}}) < ...

Can all browser console messages and errors be sent to a different machine using a pipeline?

Currently, I am in the process of troubleshooting a javascript error that is occurring within a Cordova app's InAppBrowser on an Android device. Despite being able to connect to the web-view on the phone using Chrome's remote debugging tools, the ...

I am looking to include a fresh object within a JSON object using JSONObject in Java

Trying to create a JAVA application that generates a json file containing the data sent, but encountering an issue where the new data replaces the previous data each time. The initial method called: az.addUser("John", "10", "star& ...

What is the best way to preserve the state of a component in Angular?

I need to find a way to preserve the state of a data table within my Angular 7 & Typescript application. It's essentially like saving the state of a browser tab. When I navigate to another component and return to the one with the data table, how ...

Is invoking a function from a view in AngularJS detrimental to performance?

I've observed that whenever I invoke functions from my Angular view, the functions are executed multiple times, even when the data remains unchanged. For instance: <div ng-repeat="day in days_array"> {{getWeek(day)}} </div> As a res ...

Utilize Knex - incorporating withGraphFetched and a filter condition in your query

My task involves querying the database with Knex to retrieve sales data from a specific city. Here are the two tables I am working with: sale: id drugstore_id drugstore: id name city Below are my model definitions: class Sale extends Model { static mo ...