php json合法性检查,用php的json_decode()检测json数据是否合法
作者:野牛程序员:2024-01-31 17:51:43php阅读 2677
使用 PHP 的 json_decode()
函数可以检查 JSON 数据的合法性。以下是一个简单的示例代码,演示如何使用 json_decode()
来检测 JSON 数据是否合法:
<?php // 要检测的 JSON 数据 $json_data = '{"name":"John","age":30,"city":"New York"}'; // 使用 json_decode() 解码 JSON 数据 $decoded_data = json_decode($json_data); // 检查 JSON 数据是否合法 if ($decoded_data === null && json_last_error() !== JSON_ERROR_NONE) { echo "JSON 数据不合法。"; } else { echo "JSON 数据合法。"; } ?>
在这个例子中,如果 JSON 数据不合法,json_decode()
函数返回 null
,并且可以通过 json_last_error()
函数来检索 JSON 解码的最后一个错误。如果 JSON 数据合法,json_decode()
返回解码后的数据,并且 json_last_error()
返回 JSON_ERROR_NONE
。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
