Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

Something like:

var jsonString = '{ "Id": 1, "Name": "Coke" }';  //should be true IsJsonString(jsonString);  //should be false IsJsonString("foo"); IsJsonString("<div>foo</div>") 

The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.

like image 944
Chi Chan Avatar asked Sep 14 '10 15:09

Chi Chan


People also ask

How do you check if a string is a valid JSON string in JavaScript?

To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.

How do you check if a JSON string is valid or not?

Validating with JSONObject String json = "Invalid_Json"; assertFalse(validator. isValid(json)); However, the disadvantage of this approach is that the String can be only an object but not an array using JSONObject.

Is a valid JSON character?

JSON Keys must be Valid Strings According to JSON.org, a string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. Any valid string can be used as a JSON key. These keys must be enclosed in the double-quotes ( " ).


1 Answers

Use a JSON parser like JSON.parse:

function IsJsonString(str) {     try {         JSON.parse(str);     } catch (e) {         return false;     }     return true; } 
like image 125
Gumbo Avatar answered Sep 20 '22 13:09

Gumbo