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.
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.
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.
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 ( " ).
Use a JSON parser like JSON.parse
:
function IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With