The following code throws me this exception:
$return = json_decode($result);
Fatal error: Cannot access property started with '\0' in
file.php on line
36
I've read php documentation and some questions here, so I've tried this code:
try{
$return = json_decode($result);
}
catch(Exception $e)
{
$json_error_code = json_last_error();
echo $json_error_code . ",";
$err.= 'JSON parse error';
switch ($json_error_code) {
case JSON_ERROR_NONE:
$err = "NONE";
break;
case JSON_ERROR_DEPTH:
$err.= ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$err.= ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$err.= ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$err.= ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$err.= ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$err.= ' - Unknown error';
break;
}
echo $err;
}
It throws the same Fatal error - in a try-catch block!
Can someone help me solve this?
Thanks!
Firstly remove try catch block json_decode does not throw exceptions.
Secondly create $err change the line
$err.= 'JSON parse error';
to
$err= 'JSON parse error';
You try to do concatenate strings to variable that does not exists.
Remove also break from default: it's useless.
After you do it it should work.
Notice: If you want errors to behave like exceptions you need to use own error handler
If json_encode gives you fatal error then try reinstalling json extension and see https://bugs.php.net/bug.php?id=68546
Related
"op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}"
I'm passing the JSON body above to my PHP backend and when trying to use json_decode on it, it results in null. I've used json_last_error() and it states there is a syntax issue. Using jsonlint.com, it gives me this error:
Error: Parse error on line 1:
"op=add&item={"firstName ":"test "
---------------^
Expecting 'EOF', '}', ':', ',', ']', got 'undefined'
I've tried troubleshooting this error but haven't been able to get a successful response. Can someone describe what the issue could be?
For json_decode() to work, it requires a string.
Looking at you syntax, it seems the outer quotes aren't correct.
Yours:
"op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}"
As they should be:
'op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}'
If you use single quotes, it's a correct string. Which can be decoded.
Your "body" isn't a JSON string, only the item parameter content looks like one. Take that content and pass to the function json_decode.
Example:
json_decode($_GET['item']);
this is a useful function to debug json issues
function json_validate($string){
// decode the JSON data
$result = json_decode($string);
// switch and check possible JSON errors
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = ''; // JSON is valid // No error has occurred
break;
case JSON_ERROR_DEPTH:
$error = 'The maximum stack depth has been exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON.';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Control character error, possibly incorrectly encoded.';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error, malformed JSON.';
break;
// PHP >= 5.3.3
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_RECURSION:
$error = 'One or more recursive references in the value to be encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_INF_OR_NAN:
$error = 'One or more NAN or INF values in the value to be encoded.';
break;
case JSON_ERROR_UNSUPPORTED_TYPE:
$error = 'A value of a type that cannot be encoded was given.';
break;
default:
$error = 'Unknown JSON error occured.';
break;
}
if ($error !== '') {
// throw the Exception or exit // or whatever :)
exit($error);
}
// everything is OK
return $result;
}
I'm trying to use the V2.2 of StackExchange api with PHP. I'm using the Symfony project with Kriswallsmith's buzz library.
The problem comes when I try to print the content of response of HTTP request and its encode. I have already read lots of question related with this problem in StackOverflow but the problem still exists.
This is a portion of code where I show the problem:
echo "The url: ";
var_dump($url);
var_dump($response);
$content = $response->getContent();
echo "Json decode's content: ";
var_dump(json_decode($content, true));
echo "The error is";
switch(json_last_error()) {
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Invalid or malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
}
die();
This returns the following:
If you paste the
https://api.stackexchange.com/2.2/answers?site=stackoverflow&sort=activity&
in the browser, it returns a valid JSON.
It occurs to me that for some reason the content is not ungzipped:
$ curl https://api.stackexchange.com/2.2/answers
�VJ-*�/��LQ�210ЁrsS���S����3KR2��R
K3�RS�`J�sA�I�)��E#NIj�R-g��PP
$ curl https://api.stackexchange.com/2.2/answers | gzip -d
{"error_id":400,"error_message":"site is required","error_name":"bad_parameter"}
You should be able to use PHP's gzuncompress function or dig Buzz a bit.
This is a json api : https://jobs.github.com/positions.json?description=java&page=1
I want get the data from this url.
<?php
$url = file_get_contents('https://jobs.github.com/positions.json?description=java&page=1');
var_dump(json_decode($url,true)); ?>
this code return null
I also check the url in json validator: http://jsonformatter.curiousconcept.com/ the json is valid but i con't able get the data from this url please help me...
Try this script to determine what the problem is. If there is no JSON module installed (see #julian comment), you can try to use PHP implementations of JSON like this: http://pear.php.net/pepr/pepr-proposal-show.php?id=198
if (! extension_loaded('json')) {
echo 'Module JSON not available!';
exit();
}
$url = file_get_contents('https://jobs.github.com/positions.json?description=java&page=1');
$data = json_decode($url,true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
So basically I have the code which is giving me the message from json_last_error():
$msg = 'Unknown error';
switch (json_last_error()) {
case JSON_ERROR_NONE:
$msg = null;
break;
case JSON_ERROR_DEPTH:
$msg = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$msg = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$msg = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$msg = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
}
return $msg;
For testing purposes I want to raise all the errors from this list to have 100% coverage, but I can't raise JSON_ERROR_STATE_MISMATCH.
Can anyone help giving me the example with either encoding or decoding, with any parameters, which can produce this error?
$j = '{"j": 1 ] }';
json_decode($j);
var_dump(json_last_error() === JSON_ERROR_STATE_MISMATCH); // true
How I found it: just checked the source code :-)
My web host is running PHP 5.3, but for some reason I cannot use Json_decode(). Why is that? How can I make it work? Are there any alternatives to Json_decode()?
I am using it like this:
$data= json_decode($_POST['moment']);
var_dump($_POST['moment']);
foreach($data as $item) {
echo $item;
And it outputs this:
string(22) "[\"36\",\"37\",\"38\"]"
Warning: Invalid argument supplied for foreach() on line 23
By doing the var_dump() I see the string is created, but I cannot get json_decode to work, to create the array $data
Thanks
json_decode returns NULL when the string you ask it to decode is not valid. You can use json_last_error to diagnose the issue.
When you are going to loop an array like that, you should make sure the value is actually an array.
$data= json_decode($_POST['moment'], true);
if (!is_array($data)) {
echo json_error_string(json_last_error());
} else {
foreach($data as $item) {
echo $item;
}
}
Based on code from the manual:
function json_error_string ($json_error_code) {
switch ($json_error_code) {
case JSON_ERROR_NONE:
return ' - No errors';
break;
case JSON_ERROR_DEPTH:
return ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
return ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
return ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
return ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
return ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
return ' - Unknown error';
break;
}
}
Finally, that you aren't getting any error messages indicates you either have error_reporting off or display_errors off. You need to enable all error reporting with error_reporting(E_ALL & E_STRICT); ini_set('display_errors', '1');. Remove that from production code, but while you're actively working, you need to be seeing all the information possible about the code you are creating.
Documentation
json_decode - http://php.net/manual/en/function.json-decode.php
json_last_error - http://php.net/manual/en/function.json-last-error.php
is_array - http://php.net/manual/en/function.is-array.php
Solved it using stripslashes():
$objJs = json_decode(stripslashes($_POST['obj']));