Question: Give an Sample of Correct JSON Object?
[{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]
Question: Can we check, JSON is valid OR Not?
Yes, we can do.
Below function check that JSON is valid or Not. (1 for valid, 0 for invalid)
function isValidJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
Question: How to check JSON is valid?
$string='[{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]';
if(isValidJson($string)){
echo "JSON is Valid"; //This will print
}else{
echo "JSON is NOT Valid";
}
Question: How to check JSON is NOT valid?
$string='[{{{{{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]';
if(isValidJson($string)){
echo "JSON is Valid";
}else{
echo "JSON is NOT Valid";//This will print
}
Question: How to check JSON is empty OR Not?
$string='{}';
$data = json_decode($string);
if(empty($data) || count($data)){
echo "JSON is empty";
}else{
echo "JSON is NOT empty";
}
Question: How to create an empty JSON?
$string='{}';
Question: How to decode JSON string in PHP?
$string='[{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]';
$data = json_decode($string);
Question: How to create JSON from php array?
$array = array('name'=>'PHP Tutorial','Description'=>'Web technology experts notes');
echo json_encode($array);
Question: What is the Correct content-type of JSON?
application/json
Question: How to convert JSON Object into PHP Object?
$string='[{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]';
$data = json_decode($string,false);
print_r($data);
Question: How to convert JSON Object into PHP Array?
$string='[{"name":"PHP ","Description":"Web technology experts notes"},{"name":"JSON","Description":"JSON Interview Questions"}]';
$data = json_decode($string,true);
print_r($data);
Question: How to get JSON error?
$string='Invalid JSON'; json_decode($string); echo json_last_error(); //4
Question: How to get JSON error Message?
$string='Invalid JSON'; json_decode($string); echo json_last_error_msg (); //Syntax error
