note 110820 added to function.json-decode
| From: | skypppher at gmail dot com | Date: | Tue, 11 Dec 2012 19:40:06 +0000 |
| Subject: | note 110820 added to function.json-decode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-192476@lists.php.net to get a copy of this message | ||
First of all, since JSON is not native PHP format or even native JavaScript format, everyone who
wants to use JSON wisely should carefuly read official documentation. There is a link to it here, in
"Introduction" section. Many questions like "it doesn't recognize my
strings" and those like previous one (about zip codes) will drop if you will be attentive!
And second. I've found that there is no good, real working example of how to validate string if
it is a JSON or not.
There are two ways to make this: parse input string for yourself using regular expressions or
anything else, use json_decode to do it for you.
Parsing for yourself is like writing your own compiler, too difficult.
Just testing result of json_decode is not enough because you should test it with NULL, but valid
JSON could be like this 'null' and it will evaluate to NULL. So you should use another
function - json_last_error. It will return error code of the last encode/decode operation. If no
error occured it will be JSON_ERROR_NONE. So here is the function you should use for testing:
<?php
function isValidJson($strJson) {
json_decode($strJson);
return (last_json_error() === JSON_ERROR_NONE);
}
?>
It's so simple, that there is no need to use it and slow down your script with extra delay for
function call. Just do it manualy in you code while working with input data:
<?php
//here is my initial string
$sJson = $_POST['json'];
//try to decode it
$json = json_decode($sJson);
if (last_json_error() === JSON_ERROR_NONE) {
//do something with $json. It's ready to use
} else {
//yep, it's not JSON. Log error or alert someone or do nothing
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 72.52.91.2 (proxied: 79.165.147.233)
----
Manual Page -- http://php.net/manual/en/function.json-decode.php
Edit -- https://master.php.net/note/edit/110820
Del: integrated -- https://master.php.net/note/delete/110820/integrated
Del: useless -- https://master.php.net/note/delete/110820/useless
Del: bad code -- https://master.php.net/note/delete/110820/bad+code
Del: spam -- https://master.php.net/note/delete/110820/spam
Del: non-english -- https://master.php.net/note/delete/110820/non-english
Del: in docs -- https://master.php.net/note/delete/110820/in+docs
Del: other reasons-- https://master.php.net/note/delete/110820
Reject -- https://master.php.net/note/reject/110820
Search -- https://master.php.net/manage/user-notes.php