Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect JSON support in javascript?

I tried to detect JSON support with if(JSON.parse) {} but it doesn't works. Is there any way to detect the JSON support?

like image 994
Danny Fox Avatar asked Mar 14 '12 09:03

Danny Fox


People also ask

How do I check if JSON is valid?

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.

How do you check JSON is parsed or not 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.

Does JavaScript support 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.

How do I check if an object is in JSON?

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; } };


1 Answers

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)

like image 53
xanatos Avatar answered Oct 15 '22 19:10

xanatos