Is there a foolproof method to confirm the validity of this string as JSON?

I am currently developing an application that requires a function to validate whether a given string parameter is valid JSON. The challenge lies in handling JSON data copied from Jira. For example, the JSON might appear as follows:

"{
    "query": {
        "size": 0,
        "aggregations": {
            "ipTag": {
                "terms": {
                    "field": "ipTag",
                    "size": 1001
                }
            }
        }
    },
    "table": "ip_info_table"
}"

It is unclear whether the unusual format of the string parameter is due to copying and pasting from Jira, or if it is related to MUI Input controls. When I paste the variable into a CDT watch, it appears like this:

"{\n    \"query\": {\n        \"size\": 0,\n ...."
  • While JSON.parse(param) throws an error,
  • JSON.parse(JSON.stringify(param)) returns success.
  • Surprisingly, JSON.parse(JSON.stringify('junk')) also returns success, even though a single word like 'junk' is not considered valid JSON.

What approach or code routine would you recommend for addressing this issue? Is there a specific logic that can be applied to properly format the input parameter value so that JSON.parse() validates it as JSON?

Answer №1

To ensure the validity of JSON data, I would utilize the JSON.parse method as shown below:

let valid = false;
try {
  JSON.parse(str);
  console.log('valid');
  valid = true;
} catch {
  console.log('invalid');
}
console.log(valid);

Here are some examples:

const jsonData = `{
    "query": {
        "size": 0,
        "aggregations": {
            "ipTag": {
                "terms": {
                    "field": "ipTag",
                    "size": 1001
                }
            }
        }
    },
    "table": "ip_info_table"
}`;

try {
    JSON.parse(jsonData);
    console.log('valid');
} catch {
    console.log('invalid');
}

const jsonData = "{\n    \"query\": {\n        \"size\": 0\n} }";

try {
    JSON.parse(jsonData);
    console.log('valid');
} catch {
    console.log('invalid');
}

const jsonData = `{
    "query": {
        "size": 0,
        "aggregations": {
            "ipTag": {
                "terms": {
                    "field": "ipTag",
                    "size": 1001
                }
            }
        }
    },
    "table": "ip_info_table",
}`;

try {
    JSON.parse(jsonData);
    console.log('valid');
} catch {
    console.log('invalid');
}

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

Issue with firing button click event in Node Express when using Bootstrap

Beginner in Node and ExpressJs, currently developing a Nodejs app using ExpressJS and Bootstrap with the following setup: Developing in VSCode. Tools: utilizing npm to install express and npm init to create the project Issue: Upon clicking the btnLogin ...

How to Retrieve a Scope Variable from a Controller within an Angular.js Directive

(function () { 'use strict'; angular.module('app') .controller('someController', ['$scope','localStorageService',someController]) .directive('someDirective', someDirective) function some ...

Scrolling will only function properly on this page if you refresh it

I have a setup where buttons on my first page lead to specific elements on the second page. To achieve this, I pass the element IDs in the URL like so: mysite.com/secondpage/:promo1(/2/3, depending on the button clicked.) Upon landing on the second page, ...

Recoil: Executing a function when an atom is modified

My goal is to store a user object in an atom and cache it in localStorage every time it changes to avoid having the user sign in repeatedly if the app crashes: localStorage.setItem('user', JSON.stringify(user)) Previously, with useContext, I ach ...

How can I replicate the X axis on both ends of a horizontal bar chart using only one dataset in Chart.js version 3.x?

Is there a way to duplicate the X axis ticks on both the bottom and top of a chart? I know there were solutions for older versions of Chartjs, but the options have changed in version 3.x. Previously, you could use something like this: xAxes: [ { ...

A guide on using JSONPath to parse a JSON object and filter based on a specific string value within an array nested inside the

Below is a sample JSON that I have listed down. I am looking to create a JSONPath that selects elements where the subject includes "Maths". Please note that I am utilizing Goessner's JSONPath with the Newtonsoft library in C#. { "class":{ "t ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

What could be causing the jQuery effect to not function properly?

After completing a course on Codecademy, I successfully ran the code. However, I prefer to copy and paste the code into my own jquery folder for future reference and practice. The objective of this project was to make the element 'krypton' bounc ...

Error: Parse Error - Invalid character detected during JSON parsing in C#

I am currently in the process of deciphering my jwt token. A recent addition I made to it is the inclusion of a new object named "userGroupList". This object is essentially a class that is converted into a string using JsonConvert.SerializeObject. However, ...

Encountering issues with deserializing the post body while attempting to schedule a teams meeting using PHP with the Microsoft Graph

Fetching data from Graph API endpoint POST https://graph.microsoft.com/v1.0/me/events resulted in a 400 Bad Request response: { "error": { "code":"UnableToDeserializePostBody", "message":"unable ...

Playing noughts and crosses with the minimax strategy

I am struggling with understanding the minimax algorithm and have been working on it for 2 days without success. Can anyone take a look at my code and help me identify any errors? export default class TicTacToeController { /*@ngInject*/ constructor($s ...

Managing global errors and intercepting requests in AngularJS can be easily achieved by utilizing $resource interceptors and global handlers for

My question pertains to the interceptor(responseError) of $resource. It is essential to note that I am working with angularjs version V1.3.6. The Issue: app.factory('authInterceptor',['$q', '$location', '$log', fun ...

Which kinds of scripting languages are commonly found on the client-side of browsers?

I have been researching client-side browser languages and experimenting with a few, but I feel like there may be more options out there that I'm not aware of. I am looking for a solution that can be easily processed either in the browser or on the cli ...

Performing an HTTP request response in JavaScript

I am trying to make an HTTP request that returns the data in JSON format using 'JSON.stringify(data)'. var xhr = new XMLHttpRequest(); xhr.open("GET", "/api/hello", true); xhr.send(); xhr.onreadystatechange = function () { console.log(xhr.r ...

Moving a session between a window and a modal dialog box

When I open a modal dialog from a parent window using a button click, everything works fine in WinXP with IE8. However, in Win7 with IE8, I encounter an issue where the modal dialog takes me to the login screen. Oddly enough, if I enter my credentials, clo ...

Tips for properly sending an array containing objects in JSON format using Swift for iOS development

As a beginner, I am trying to grasp the concept of sending an array with objects. Does the server recognize arrays like Int, Strings, or Booleans? Do I need to convert the array into a string for JSON data? There seems to be something I'm missing. va ...

Using jsdom as a package in a Meteor application is not possible

Recently, I came across an issue with my packages.json file. It looks like this: { "jsdom" : "0.8.0", "request" : "2.25.0" } As part of my project, I have the following code snippet: if (Meteor.isServer) { Meteor.startup(function () { var _ ...

Sending a JSON payload using a Bash script with the curl command

When attempting to POST a JSON in a bash script using curl, I encountered an error related to the content. The error message received is: Rebuilt URL to: "major":"1221",/ Illegal port number Closing connection -1 curl: (3) Illegal port number Note: Unnec ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

The client is receiving server data in the form of [Object object]

https://i.sstatic.net/L3GvX.png I'm facing an issue with displaying the data sent from the server, as it's not showing properly (showing [Object object] at the bottom left of the image). Below is the code snippet from the client side: &l ...