I want to check in client side(jQuery) whether return data from a PHP function is Json object or String to assign different function.
4 Answers
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
-
Thanks for your fast reply but I'm a little confuse with bad practice. You mean I shouldn't try to solve my problem with parseJSON's exception? – Devyn Oct 15 '10 at 19:51
-
1No, firing exceptions in normal execution is a bad practice. Exeptions should only be fired when something is wrong (when you don't expect some result) – Yarek T Oct 15 '10 at 19:52
-
Sure it is. But considering this is an answer from 6 years ago, i'm sure there are better ways to do this. I have moved on from Front end Javascript :) – Yarek T May 26 '16 at 16:12
try {
jQuery.parseJSON( json )
//must be valid JSON
} catch(e) {
//must not be valid JSON
}

- 67,365
- 22
- 157
- 181

- 7,133
- 1
- 21
- 27
Return data is always a string (i.e., a character sequence). But, if you tell jQuery you expect json response, it'll attempt to convert string into a javascript object for you.
There's no dedicated network protocol to transfer javascript objects over the internet.

- 67,365
- 22
- 157
- 181
-
3How to tell if `typeof(A) != typeof(B)`, where `A` and `B` are strings...? :-) – Oct 15 '10 at 19:42
-
2
-
`typeof` will not check if string is valid JSON. It will return both "string" for valid JSON and for random string. It is not some sort of thing OP wants. As for question - I didn't find anything except try/catch approach mentioned in accepted answer. – Serj.by Aug 29 '18 at 12:55