I tried to detect JSON support with if(JSON.parse) {}
but it doesn't works. Is there any way to detect the JSON support?
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.
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.
JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two.
To check if JavaScript object is JSON, we can use the JSON. parse method. const isJson = (data) => { try { const testIfJson = JSON. parse(data); if (typeof testIfJson === "object") { return true; } else { return false; } } catch { return false; } };
Taken from the json most famous implementation https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var JSON;
if (JSON && typeof JSON.parse === 'function') {
....
}
(I have merged the two if
: if (!JSON) {
of line 163 and if (typeof JSON.parse !== 'function') {
of line 406.
The trick here is that the var JSON
will get the value of the JSON object of the browser, undefined
if not.
Note that in the latest version of the library they changed the code to something like:
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
....
}
(without pre-declaring the var JSON
)
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