PHP: Debugging decoding JSON value problems - jsondecode()

The function jsondecode() function will help convert a json formatted string into JSON object. Using this object we can access its key value pairs of JSON content. Some cases we cannot create JSON object from the string. Below are possible reasons of cannot create JSON objects.

1. Syntax Error:
  JSON syntax may be wrong. All JSON values are enclosed by "{}". If multi-dimensional then JSON should be key value pair. There is no end semicolon for values group ending.

2. The string contains special symbols:
  Like HTML entities are needed to strip from the string before decode. 

  $string = "[{a,b,c,d,e,f,g}]";
  $string = html_entity_decode($);
  $decode = json_decode($string);
  prinr_r($decode);

3. Need to remove hidden values:
  For confidential data are encrypted with hidden values like BOM. Mostly these hidden values are used for securing the content. So we need to strip the hidden values. 

  $string = "[{a,b,c,d,e,f,g}]";
  $string = "[{a,b,c,d,e,f,g}]";
  $string = str_replace(chr(127), "", $string);
  if (0 === strpos(bin2hex($resString), 'efbbbf')) {
    $string = substr($string, 3);
  }
  $decode = json_decode($string);
  prinr_r($decode);

4. Getting Error details:
  At the end of jsondecode() we can specify json_last_error() and json_last_error_message() to get error description of JSON decode. This functions will support after PHP version 5.4

$string = "[{a,b,c,d,e,f,g}]";
$resData =  json_decode($string, true);
echo json_last_error();
echo json_last_error_msg();
Category: