I want to check in client side(jQuery) whether return data from a PHP function is Json object or String to assign different function.
JSON Check The fetch . then() callback is passed the HTTP response object when the request is completed, the function checks if the response type is JSON before parsing the response body with the response. json() method, because calling response. json() will cause an error if the response doesn't contain JSON data.
In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.
we can use json_last_error() PHP function to check validity of JSON, It returns JSON_ERROR_NONE predefined constant value if JSON successfully decoded or encoded by PHP's josn functions.
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.
jQuery's parseJson will generate an exception if the json is not in the correct format. You could wrap your call in a try catch block. (But remember that having exceptions in your normal code's flow is bad practice)
data = '{}';
try {
json = $.parseJSON(data);
} catch (e) {
// not json
}
You can also use the native JSON.parse()
method which throws a SyntaxError
exception
If you are expecting bad JSON as part of your normal program workflow then you could check it with regex first, Mic's answer is pretty solid But in your case, PHP should always generate valid json under normal conditions. If its invalid there probably is a bug in your software
try {
jQuery.parseJSON( json )
//must be valid JSON
} catch(e) {
//must not be valid 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