Javascript is json valid

Validate JSON String Using JavaScript

This article is for Validate JSON String using Javascript. It’s a JavaScript World, JavaScript is everywhere, on the browser, on the server, on mobile, on cloud and everyone uses JSON as data to pass from one end to other ends. JavaScript has an inbuilt function to parse the JSON object and which is supported by latest browsers. Before using JSON string, it has to be valid or it will throw an exception. Here is the function which validates the JSON string.

Validate JSON data using JavaScript Function.

function IsValidJSONString(str)   try   JSON.parse(str);  > catch (e)   return false;  >  return true; >

JSON.parse function will use string and converts to JSON object and if it parses invalidate JSON data, it throws an exception (“Uncaught SyntaxError: Unexpected string in JSON”).

Here is the example of Validate JSON Using Javascript.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
var validjsontext = '<"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]>';  var invalidjsontext = '<"firstnam""James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]>';  console.log("With Valid JSON Text: "+IsValidJSONString(validjsontext));  console.log("With inValid JSON Text: "+IsValidJSONString(invalidjsontext));  function IsValidJSONString(str)   try   JSON.parse(str);  > catch (e)   return false;  >  return true; >

There are tools available online to check in detail JSON validation errors. Please visit these tools for test your JSON data.

Are you also working with Python? try this Validate JSON Using Python.

Источник

Check if a String Is a Valid JSON String in JavaScript

Check if a String Is a Valid JSON String in JavaScript

  1. Difference Between JSON and Javascript Objects
  2. Check the Validity of JSON String in JavaScript

This article will teach how to check if a given string is a valid JSON or JavaScript Object Notation string without using try. catch in JavaScript. Let’s begin with the definition of JSON string and how it helps us ease our workflow.

JSON is a language-independent text format used for structuring data very similar to XML; it can consist of strings, numbers int, float, etc., Boolean, array, or Java objects (key-value pair) enclosed in curly brackets

Difference Between JSON and Javascript Objects

This is how object in JavaScript looks like:

object = :"Haseeb", age:31, city:"New York",male:true> 

When that object is saved in JSON format, it looks like this:

"name":" Haseeb ", "age":31, "city":"New York", "male":true> 

When we retrieve object back from text file it gets converted into JSON string format:

"name":" Haseeb ", "age":31, "city":"New York", "male":true> 

We can see how JSON format is human readable and easier for languages to manipulate.

It has various advantages other than that; JSON, aside from being easy to read and write, can integrate with all of the languages, and parsing can now be used conveniently because of its detailed structure.

JSON is commonly used for Application programming interfaces (APIs) since it is mainly used to transfer data to and from a server to a web or mobile application and vice versa.

By using JSON’s parse function, we can now create objects from JSON string, here’s an example of how it’s done:

string = ''; object = JSON.parse(string); console.log(object); 
  name: 'John',  age: 31,  city: 'New York',  male: true > 

As expected, the parse function trims everything down to the object’s key and value (JSON object) which is why JSON string has now become a convention to transfer data to and from between systems.

Check the Validity of JSON String in JavaScript

try. catch is used to handle any potential error that may pop up in the given JSON string without halting the program’s execution. The string could have faulty syntax, missing parameters, or perhaps a wrong splitting argument.

Here’s how we can check the validity of a JSON string using try. catch :

try   object = JSON.parse(json); > catch (error)   is_json = false;  console.log("Invalid JSON string"); > 

Let us try giving our code this string:

As we can observe, our try. catch doesn’t tell us what is wrong with the string. It simply tells us there exists some problem.

To get an insight into what is wrong in the JSON string, we may turn to our custom-made function that detects, if not all, some errors that pop up in a string without the use of try. catch .

isJSON = function(json)    //Nested Count function only to be used for counting colons and commas  countCharacter = function(string,character)   count = 0;  for (var i = 0; i  string.length; i++)   if (string.charAt(i) == character) < //counting : or ,  count ++;  >  >  return count;  >   json = json.trim(); // remove whitespace, start and end spaces   //check starting and ending brackets  if (json.charAt(0) != ' || json.charAt(json.length-1) != '>')   console.log("Brackets <> are not balanced")  return false  >  //else this line will check whether commas(,) are one less than colon(:)  else if ( !(countCharacter(json,':')-1 == countCharacter(json, ',')) )   console.log("comma or colon are not balanced");  return false;   > else    json = json.substring(1, json.length-1); //remove first and last brackets  json = json.split(','); //split string into array, and on each index there is a key-value pair   //this line iterate the array of key-value pair and check whether key-value string has colon in between  for (var i = 0; i  json.length; i++)    pairs = json[i];   if (pairs.indexOf(':') == -1) < //if colon not exist in b/w   console.log("No colon b/w key and value");  return false;  >  >  >  return true; >; 

Let’s use the two JSON strings and find their faults.

comma or colon are not balanced false 
Brackets <> are not balanced false 

This code is weak since it is true for some false cases, so we find a hybrid approach to merge both the upper function and try. catch code to get an absolute answer with some debugging.

isJSON = function(json)    is_json = true; //true at first   //Try-catch and JSON.parse function is used here.   try   object = JSON.parse(json);  > catch (error)   is_json = false;  console.log("might be a problem in key or value's data type");  >   if (!is_json)   countCharacter = function(string,character)   count = 0;  for (var i = 0; i  string.length; i++)   if (string.charAt(i) == character) < //counting : or ,  count ++;  >  >  return count;  >   json = json.trim(); // remove whitespace, start and end spaces   if (json.charAt(0) != ' || json.charAt(json.length-1) != '>')   console.log("Brackets <> are not balanced")   >   else if ( !(countCharacter(json,':')-1 == countCharacter(json, ',')) )   console.log("comma or colon are not balanced");   > else    json = json.substring(1, json.length-1); //remove first and last brackets  json = json.split(',');   for (var i = 0; i  json.length; i++)    pairs = json[i];  if (pairs.indexOf(':') == -1) < //if colon not exist in b/w  console.log("No colon b/w key and value");  >  >  >  >  return is_json; >; 
might be a problem in key or value's data type false 

This function is given the same debugging level as the previous function, but the answer will be absolute this time.

Related Article — JavaScript JSON

Источник

Check if a String Is a Valid JSON String in JavaScript

Check if a String Is a Valid JSON String in JavaScript

  1. Difference Between JSON and Javascript Objects
  2. Check the Validity of JSON String in JavaScript

This article will teach how to check if a given string is a valid JSON or JavaScript Object Notation string without using try. catch in JavaScript. Let’s begin with the definition of JSON string and how it helps us ease our workflow.

JSON is a language-independent text format used for structuring data very similar to XML; it can consist of strings, numbers int, float, etc., Boolean, array, or Java objects (key-value pair) enclosed in curly brackets

Difference Between JSON and Javascript Objects

This is how object in JavaScript looks like:

object = :"Haseeb", age:31, city:"New York",male:true> 

When that object is saved in JSON format, it looks like this:

"name":" Haseeb ", "age":31, "city":"New York", "male":true> 

When we retrieve object back from text file it gets converted into JSON string format:

"name":" Haseeb ", "age":31, "city":"New York", "male":true> 

We can see how JSON format is human readable and easier for languages to manipulate.

It has various advantages other than that; JSON, aside from being easy to read and write, can integrate with all of the languages, and parsing can now be used conveniently because of its detailed structure.

JSON is commonly used for Application programming interfaces (APIs) since it is mainly used to transfer data to and from a server to a web or mobile application and vice versa.

By using JSON’s parse function, we can now create objects from JSON string, here’s an example of how it’s done:

string = ''; object = JSON.parse(string); console.log(object); 
  name: 'John',  age: 31,  city: 'New York',  male: true > 

As expected, the parse function trims everything down to the object’s key and value (JSON object) which is why JSON string has now become a convention to transfer data to and from between systems.

Check the Validity of JSON String in JavaScript

try. catch is used to handle any potential error that may pop up in the given JSON string without halting the program’s execution. The string could have faulty syntax, missing parameters, or perhaps a wrong splitting argument.

Here’s how we can check the validity of a JSON string using try. catch :

try   object = JSON.parse(json); > catch (error)   is_json = false;  console.log("Invalid JSON string"); > 

Let us try giving our code this string:

As we can observe, our try. catch doesn’t tell us what is wrong with the string. It simply tells us there exists some problem.

To get an insight into what is wrong in the JSON string, we may turn to our custom-made function that detects, if not all, some errors that pop up in a string without the use of try. catch .

isJSON = function(json)    //Nested Count function only to be used for counting colons and commas  countCharacter = function(string,character)   count = 0;  for (var i = 0; i  string.length; i++)   if (string.charAt(i) == character) < //counting : or ,  count ++;  >  >  return count;  >   json = json.trim(); // remove whitespace, start and end spaces   //check starting and ending brackets  if (json.charAt(0) != ' || json.charAt(json.length-1) != '>')   console.log("Brackets <> are not balanced")  return false  >  //else this line will check whether commas(,) are one less than colon(:)  else if ( !(countCharacter(json,':')-1 == countCharacter(json, ',')) )   console.log("comma or colon are not balanced");  return false;   > else    json = json.substring(1, json.length-1); //remove first and last brackets  json = json.split(','); //split string into array, and on each index there is a key-value pair   //this line iterate the array of key-value pair and check whether key-value string has colon in between  for (var i = 0; i  json.length; i++)    pairs = json[i];   if (pairs.indexOf(':') == -1) < //if colon not exist in b/w   console.log("No colon b/w key and value");  return false;  >  >  >  return true; >; 

Let’s use the two JSON strings and find their faults.

comma or colon are not balanced false 
Brackets <> are not balanced false 

This code is weak since it is true for some false cases, so we find a hybrid approach to merge both the upper function and try. catch code to get an absolute answer with some debugging.

isJSON = function(json)    is_json = true; //true at first   //Try-catch and JSON.parse function is used here.   try   object = JSON.parse(json);  > catch (error)   is_json = false;  console.log("might be a problem in key or value's data type");  >   if (!is_json)   countCharacter = function(string,character)   count = 0;  for (var i = 0; i  string.length; i++)   if (string.charAt(i) == character) < //counting : or ,  count ++;  >  >  return count;  >   json = json.trim(); // remove whitespace, start and end spaces   if (json.charAt(0) != ' || json.charAt(json.length-1) != '>')   console.log("Brackets <> are not balanced")   >   else if ( !(countCharacter(json,':')-1 == countCharacter(json, ',')) )   console.log("comma or colon are not balanced");   > else    json = json.substring(1, json.length-1); //remove first and last brackets  json = json.split(',');   for (var i = 0; i  json.length; i++)    pairs = json[i];  if (pairs.indexOf(':') == -1) < //if colon not exist in b/w  console.log("No colon b/w key and value");  >  >  >  >  return is_json; >; 
might be a problem in key or value's data type false 

This function is given the same debugging level as the previous function, but the answer will be absolute this time.

Related Article — JavaScript JSON

Источник

Читайте также:  Complex комплексное число python
Оцените статью