要在 PHP 中判断给定的字符串是否是 JSON,可以使用 json_decode()
函数和检查返回值的类型。以下是一个示例,展示了如何判断给定的字符串是否是 JSON,以及如何判断它是数组还是字符串:
<?php
function isJson($string)
{
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
$jsonString1 = '{"name": "John","age": 30,"city": "New York"}';
$jsonString2 = '["apple","orange","banana"]';
$notJsonString1 = 'This is not a JSON string';
$notJsonString2 = '"This is a JSON string,but it is a string,not an object or array"';
// 测试 JSON 字符串
var_dump(isJson($jsonString1)); // 输出:bool(true)
var_dump(isJson($jsonString2)); // 输出:bool(true)
// 测试非 JSON 字符串
var_dump(isJson($notJsonString1)); // 输出:bool(false)
var_dump(isJson($notJsonString2)); // 输出:bool(false)
// 判断 JSON 字符串是数组还是字符串
$decoded1 = json_decode($jsonString1,true);
$decoded2 = json_decode($jsonString2,true);
if (is_array($decoded1)) {
echo "The first JSON string is an array.\n";
} else {
echo "The first JSON string not is an array.\n";
}
if (is_array($decoded2)) {
echo "The second JSON string is an array.\n";
} else {
echo "The second JSON string not is an array.\n";
}
?>
在这个示例中,我们定义了一个名为 isJson()
的函数,用于检查给定的字符串是否是 JSON。然后,我们使用 json_decode()
函数解码 JSON 字符串,并使用 is_array()
函数检查解码后的值的类型。如果解码后的值是数组,则 JSON 字符串是数组。
原文地址:https://blog.csdn.net/q8688/article/details/135334505
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。