【PHP】判断字符串是否是json类型,并判断是否是有效数组

要在 PHP 中判断给定的字符串是否是 JSON,可以使用 json_decode() 函数和检查返回值的类型。以下是一个示例,展示了如何判断给定的字符串是否是 JSON,以及如何判断它是数组还是字符串:

php 复制代码
<?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 字符串是数组。

相关推荐
摩西蒙9 小时前
计算机网络
开发语言·计算机网络·php
SQDN10 小时前
Chatbox 1.22.1 获取不到模型?先验 /models,再对齐精确 model ID
人工智能·测试工具·机器学习·chatgpt·json
Sagittarius_A*14 小时前
【RCELABS】Level 17~18 —— PHP命令执行函数与环境变量注入
开发语言·安全·web安全·靶场·php·rce
破碎的南瓜14 小时前
靶场中使用到的php函数以及每种漏洞的防御方式
开发语言·php
谁看我谁 狼家二丫15 小时前
局域网文件共享实战:从“账户被禁用”到成功互传文件
开发语言·php
AC赳赳老秦15 小时前
软著公开信息批量采集:OpenClaw 抓取软件著作权公开数据,分析企业技术布局方向
大数据·网络·人工智能·python·php·deepseek·openclaw
梓仁沐白16 小时前
【Agent 设计模式】多智能体协作
microsoft·设计模式·php
开源推荐官16 小时前
刚上架的商品搜不到,tigshop开源商城搜索是怎么查的
mysql·开源·php
SunnyDays101116 小时前
Python 将 Excel(XLS/XLSX)转换为 JSON:导出工作簿、工作表、单元格区域与自定义 JSON 结构
python·json·excel·excel 转 json·导出 excel 到 json·xlsx 转 json·xls 转 json
Dxy123931021618 小时前
TCP三次握手和四次挥手的过程详解
网络·tcp/ip·php