0

I need a function to check whether the incomming response is JSON or NOT in PHP

For eg. my JSON is this

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
zzlalani
  • 22,960
  • 16
  • 44
  • 73
user2324085
  • 63
  • 1
  • 3
  • 11

4 Answers4

0

You could use json_decode() on it and then check json_last_error(). If you have an error, it's not valid JSON.

Keep in mind it's not good enough to just check for null. The string null is valid JSON (and it decodes as such).

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
-1

Yes you can validate Like this.

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

    if($json) {
       $ob = json_decode($json);
       if($ob === null) {
           echo 'Invalid Json';
       } else {
          echo 'Valid Json';
       }
    }
Roopendra
  • 7,674
  • 16
  • 65
  • 92
-1
$json_request = (json_decode($request) != NULL) ? true : false;

Taken from: PHP check whether Incoming Request is JSON type

Does that work?

Community
  • 1
  • 1
Hawiak
  • 553
  • 1
  • 9
  • 32
  • You shouldn't just grab an answer from another and post it, even with attribution. It'd be better to close this as a duplicate (or if you can't due to low rep, flag it perhaps). – alex Nov 26 '13 at 05:28
  • Im sorry, just wanted to help, wont do that again – Hawiak Nov 26 '13 at 05:29
  • I'm sure your intentions were good. :) – alex Nov 26 '13 at 05:33
-1

use this

function check_whether_json($response){
    if(json_decode($response) != NULL){
        return TRUE;
    }else{
        return FALSE;
    }
}

and CHECK like this

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

Now Checking Starts

if(check_whether_json($json)){
// Proceed ur code...
}
Mohan Raj
  • 447
  • 1
  • 5
  • 18
  • [`null` is valid JSON](http://codepad.org/p1690dQg). You could also return the results of that condition, I don't believe you gain anything by repeating the return value. – alex Nov 26 '13 at 05:30