检查字符串是否是PHP中的JSON的最快方法?

时间:2011-05-18 08:18:03

标签: php json error-handling json-deserialization jsonresult

我需要一种非常非常快速的检查字符串是否为JSON的方法。我觉得这不是最好的方式:

function isJson($string) {
    return ((is_string($string) &&
            (is_object(json_decode($string)) ||
            is_array(json_decode($string))))) ? true : false;
}

那里的任何表演爱好者都希望改进这种方法吗?

31 个答案:

答案 0 :(得分:514)

function isJson($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

答案 1 :(得分:142)

  

回答问题

函数json_last_error返回JSON编码和解码期间发生的最后一个错误。因此,检查有效JSON的最快方法是

// decode the JSON data
// set second parameter boolean TRUE for associative array output.
$result = json_decode($json);

if (json_last_error() === JSON_ERROR_NONE) {
    // JSON is valid
}

// OR this is equivalent

if (json_last_error() === 0) {
    // JSON is valid
}

请注意,PHP> = 5.3.0仅支持json_last_error

  

检查确切错误的完整程序

在开发期间知道确切的错误总是好的。这是完整的程序,可以根据PHP文档检查确切的错误。

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;
}
  

使用有效JSON INPUT进行测试

$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
$output = json_validate($json);
print_r($output);
  

有效输出

Array
(
    [0] => stdClass Object
        (
            [user_id] => 13
            [username] => stack
        )

    [1] => stdClass Object
        (
            [user_id] => 14
            [username] => over
        )
)
  

使用无效的JSON进行测试

$json = '{background-color:yellow;color:#000;padding:10px;width:650px;}';
$output = json_validate($json);
print_r($output);
  

无效的输出

Syntax error, malformed JSON.
  

额外注意事项(PHP> = 5.2&& PHP< 5.3.0)

由于PHP 5.2不支持json_last_error,您可以检查编码或解码是否返回布尔值FALSE。这是一个例子

// decode the JSON data
$result = json_decode($json);
if ($result === FALSE) {
    // JSON is invalid
}

希望这有帮助。快乐的编码!

答案 2 :(得分:70)

你真正需要做的就是......

if (is_object(json_decode($MyJSONArray))) 
    { 
        ... do something ...
    }

此请求甚至不需要单独的功能。只需在json_decode周围包装is_object并继续。似乎这个解决方案让人们过分考虑它。

答案 3 :(得分:69)

使用json_decode“探测”它实际上可能不是最快的方法。如果它是一个深度嵌套的结构,那么实例化大量的数组对象只是扔掉它们是浪费内存和时间。

因此,使用preg_match RFC4627正则表达式以及确保有效性可能会更快:

  // in JS:
  var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
         text.replace(/"(\\.|[^"\\])*"/g, '')));

在PHP中也一样:

  return !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/',
       preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_string));

然而,没有足够的表演爱好者在这里打扰基准。

答案 4 :(得分:29)

如果你的字符串代表 json数组或对象,这将返回 true

function isJson($str) {
    $json = json_decode($str);
    return $json && $str != $json;
}

它拒绝只包含数字,字符串或布尔值的json字符串,尽管这些字符串在技术上是有效的json。

var_dump(isJson('{"a":5}')); // bool(true)
var_dump(isJson('[1,2,3]')); // bool(true)
var_dump(isJson('1')); // bool(false)
var_dump(isJson('1.5')); // bool(false)
var_dump(isJson('true')); // bool(false)
var_dump(isJson('false')); // bool(false)
var_dump(isJson('null')); // bool(false)
var_dump(isJson('hello')); // bool(false)
var_dump(isJson('')); // bool(false)

这是我能想到的最短路。

答案 5 :(得分:19)

我使用的最简单,最快捷的方式是:

$json_array = json_decode( $raw_json , true );

if( $json_array == NULL )   //check if it was invalid json string
    die ('Invalid');  // Invalid JSON error

 // you can execute some else condition over here in case of valid JSON

这是因为如果输入的字符串不是json或无效的json,json_decode()将返回NULL。


验证JSON

的简单功能

如果必须在多个位置验证JSON,可以始终使用以下功能。

function is_valid_json( $raw_json ){
    return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}

在上面的函数中,如果它是一个有效的JSON,你将得到回报。

答案 6 :(得分:17)

function is_json($str){ 
    return json_decode($str) != null;
}
检测到无效编码时,

http://tr.php.net/manual/en/function.json-decode.php返回值为空。

答案 7 :(得分:11)

您必须验证输入以确保您传递的字符串不为空,并且实际上是一个字符串。空字符串无效JSON。

function is_json($string) {
  return !empty($string) && is_string($string) && is_array(json_decode($string, true)) && json_last_error() == 0;
}

我认为在PHP中确定JSON对象是否具有数据更为重要,因为要使用您需要调用json_encode()json_decode()的数据。我建议拒绝空的JSON对象,这样就不会不必要地对空数据运行编码和解码。

function has_json_data($string) {
  $array = json_decode($string, true);
  return !empty($string) && is_string($string) && is_array($array) && !empty($array) && json_last_error() == 0;
}

答案 8 :(得分:9)

昨天,我在工作中遇到类似问题后发现了这个问题。最后,我的解决方案是上述某些方法的混合:

function is_JSON($string) {

  return (is_null(json_decode($string, TRUE))) ? FALSE : TRUE;

}

答案 9 :(得分:8)

这可以做到:

function isJson($string) {
    $decoded = json_decode($string); // decode our JSON string
    if ( !is_object($decoded) && !is_array($decoded) ) {
        /*
        If our string doesn't produce an object or array
        it's invalid, so we should return false
        */
        return false;
    }
    /*
    If the following line resolves to true, then there was
    no error and our JSON is valid, so we return true.
    Otherwise it isn't, so we return false.
    */
    return (json_last_error() == JSON_ERROR_NONE);
}

if ( isJson($someJsonString) ) {
    echo "valid JSON";
} else {
    echo "not valid JSON";
}

如其他答案所示,json_last_error()返回上一个json_decode()中的任何错误。但是,在某些边缘用例中,仅此功能还不够全面。例如,如果您json_decode()一个整数(例如:123)或一串没有空格或其他字符的数字(例如:"123"),则json_last_error()函数不会捕获错误。

为解决这个问题,我添加了一个额外的步骤,以确保我们的json_decode()的结果是对象还是数组。如果不是,那么我们返回false

要查看实际效果,请查看以下两个示例:

答案 10 :(得分:7)

将PHPBench与以下类一起使用,可获得以下结果:

<?php

declare(strict_types=1);

/**
 * @Revs(1000)
 * @Iterations(100)
 */
class BenchmarkJson
{
    public function benchCatchValid(): bool
    {
        $validJson = '{"validJson":true}';
        try {
            json_decode($validJson, true, 512, JSON_THROW_ON_ERROR);
            return true;
        } catch(\JsonException $exception) {}
        return false;
    }

    public function benchCatchInvalid(): bool
    {
        $invalidJson = '{"invalidJson"';
        try {
            json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
            return true;
        } catch(\JsonException $exception) {}
        return false;
    }

    public function benchLastErrorValid(): bool
    {
        $validJson = '{"validJson":true}';
        json_decode($validJson, true);
        return (json_last_error() === JSON_ERROR_NONE);
    }

    public function benchLastErrorInvalid(): bool
    {
        $invalidJson = '{"invalidJson"';
        json_decode($invalidJson, true);
        return (json_last_error() === JSON_ERROR_NONE);
    }

    public function benchNullValid(): bool
    {
        $validJson = '{"validJson":true}';
        return (json_decode($validJson, true) !== null);
    }

    public function benchNullInvalid(): bool
    {
        $invalidJson = '{"invalidJson"';
        return (json_decode($invalidJson, true) !== null);
    }
}

6 subjects, 600 iterations, 6,000 revs, 0 rejects, 0 failures, 0 warnings
(best [mean mode] worst) = 0.714 [1.203 1.175] 1.073 (μs)
⅀T: 721.504μs μSD/r 0.089μs μRSD/r: 7.270%
suite: 1343ab9a3590de6065bc0bc6eeb344c9f6eba642, date: 2020-01-21, stime: 12:50:14
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+
| benchmark     | subject               | set | revs | its | mem_peak   | best    | mean    | mode    | worst   | stdev   | rstdev | diff  |
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+
| BenchmarkJson | benchCatchValid       | 0   | 1000 | 100 | 2,980,168b | 0.954μs | 1.032μs | 1.016μs | 1.428μs | 0.062μs | 6.04%  | 1.33x |
| BenchmarkJson | benchCatchInvalid     | 0   | 1000 | 100 | 2,980,184b | 2.033μs | 2.228μs | 2.166μs | 3.001μs | 0.168μs | 7.55%  | 2.88x |
| BenchmarkJson | benchLastErrorValid   | 0   | 1000 | 100 | 2,980,184b | 1.076μs | 1.195μs | 1.169μs | 1.616μs | 0.083μs | 6.97%  | 1.54x |
| BenchmarkJson | benchLastErrorInvalid | 0   | 1000 | 100 | 2,980,184b | 0.785μs | 0.861μs | 0.863μs | 1.132μs | 0.056μs | 6.54%  | 1.11x |
| BenchmarkJson | benchNullValid        | 0   | 1000 | 100 | 2,980,168b | 0.985μs | 1.124μs | 1.077μs | 1.731μs | 0.114μs | 10.15% | 1.45x |
| BenchmarkJson | benchNullInvalid      | 0   | 1000 | 100 | 2,980,184b | 0.714μs | 0.775μs | 0.759μs | 1.073μs | 0.049μs | 6.36%  | 1.00x |
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+

结论:检查json是否有效的最快方法是返回json_decode($json, true) !== null)

答案 11 :(得分:7)

简单方法是检查json结果..

Dir["#{File.dirname(__FILE__)}/crawler/**/*.rb"].each { |file| load(file) }

答案 12 :(得分:5)

GuzzleHttp中的

/**
 * Wrapper for json_decode that throws when an error occurs.
 *
 * @param string $json    JSON data to parse
 * @param bool $assoc     When true, returned objects will be converted
 *                        into associative arrays.
 * @param int    $depth   User specified recursion depth.
 * @param int    $options Bitmask of JSON decode options.
 *
 * @return mixed
 * @throws \InvalidArgumentException if the JSON cannot be decoded.
 * @link http://www.php.net/manual/en/function.json-decode.php
 */
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
    $data = \json_decode($json, $assoc, $depth, $options);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_decode error: ' . json_last_error_msg());
    }

    return $data;
}

/**
 * Wrapper for JSON encoding that throws when an error occurs.
 *
 * @param mixed $value   The value being encoded
 * @param int    $options JSON encode option bitmask
 * @param int    $depth   Set the maximum depth. Must be greater than zero.
 *
 * @return string
 * @throws \InvalidArgumentException if the JSON cannot be encoded.
 * @link http://www.php.net/manual/en/function.json-encode.php
 */
function json_encode($value, $options = 0, $depth = 512)
{
    $json = \json_encode($value, $options, $depth);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_encode error: ' . json_last_error_msg());
    }

    return $json;
}

答案 13 :(得分:5)

//Tested thoroughly, Should do the job:
public static function is_json(string $json):bool
{
    json_decode($json);
    if (json_last_error() === JSON_ERROR_NONE) {
        return true;
    }
    return false;
}

答案 14 :(得分:5)

早些时候我只是检查一个空值,实际上这是错误的。

    $data = "ahad";
    $r_data = json_decode($data);
    if($r_data){//json_decode will return null, which is the behavior we expect
        //success
    }

上面的代码可以正常使用字符串。但是,只要我提供号码,它就会中断。例如。

    $data = "1213145";
    $r_data = json_decode($data);

    if($r_data){//json_decode will return 1213145, which is the behavior we don't expect
        //success
    }

为了解决这个问题,我所做的非常简单。

    $data = "ahad";
    $r_data = json_decode($data);

    if(($r_data != $data) && $r_data)
        print "Json success";
    else
        print "Json error";

答案 15 :(得分:4)

我们需要检查传递的字符串是否不是数字,因为在这种情况下json_decode不会引发错误。

  Building in workspace C:\Users\Anishas\.jenkins\workspace\Sample123
    Cloning the remote Git repository
    Cloning repository https://github.com/AnishaSalunkhe/HelloWorld.git
     > C:\Users\Anishas\git init C:\Users\Anishas\.jenkins\workspace\Sample123 # timeout=10
    ERROR: Error cloning remote repo 'origin'
    hudson.plugins.git.GitException: Could not init C:\Users\Anishas\.jenkins\workspace\Sample123
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$5.execute(CliGitAPIImpl.java:656)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:463)
        at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1057)
        at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1097)
        at hudson.scm.SCM.checkout(SCM.java:485)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1269)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:607)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529)
        at hudson.model.Run.execute(Run.java:1738)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:98)
        at hudson.model.Executor.run(Executor.java:410)
    Caused by: hudson.plugins.git.GitException: Error performing command: C:\Users\Anishas\git init C:\Users\Anishas\.jenkins\workspace\Sample123
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1726)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1695)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1691)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommand(CliGitAPIImpl.java:1321)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$5.execute(CliGitAPIImpl.java:654)
        ... 12 more
    Caused by: java.io.IOException: Cannot run program "C:\Users\Anishas\git" (in directory "C:\Users\Anishas\.jenkins\workspace\Sample123"): CreateProcess error=5, Access is denied
        at java.lang.ProcessBuilder.start(Unknown Source)
        at hudson.Proc$LocalProc.<init>(Proc.java:240)
        at hudson.Proc$LocalProc.<init>(Proc.java:212)
        at hudson.Launcher$LocalLauncher.launch(Launcher.java:815)
        at hudson.Launcher$ProcStarter.start(Launcher.java:381)
        at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1715)
        ... 16 more
    Caused by: java.io.IOException: CreateProcess error=5, Access is denied
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        ... 22 more
    ERROR: null
    Finished: FAILURE

答案 16 :(得分:4)

另一种简单方法

function is_json($str)
{
    return is_array(json_decode($str,true));
}

答案 17 :(得分:3)

我已尝试过其中一些解决方案,但没有任何对我有用。我尝试这个简单的事情:

$isJson = json_decode($myJSON);

if ($isJson instanceof \stdClass || is_array($isJson)) {
   echo("it's JSON confirmed");
} else {
   echo("nope");
}

我认为这是一个很好的解决方案,因为没有第二个参数的JSON解码会给出一个对象。

编辑:如果您知道输入的内容,您可以根据需要调整此代码。在我的情况下,我知道我有一个以“{”开头的Json,所以我不需要检查它是否是一个数组。

答案 18 :(得分:1)

展开this answer以下内容如何:

public sealed class WinAPI
{
    [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
    public static extern int GetSystemMetrics(int which);

    [DllImport("user32.dll")]
    public static extern void
        SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
                     int X, int Y, int width, int height, uint flags);

    private const int SM_CXSCREEN = 0;
    private const int SM_CYSCREEN = 1;
    private static IntPtr HWND_TOP = IntPtr.Zero;
    private const int SWP_SHOWWINDOW = 64; // 0×0040

    public static int ScreenX
    {
        get { return GetSystemMetrics(SM_CXSCREEN); }
    }

    public static int ScreenY
    {
        get { return GetSystemMetrics(SM_CYSCREEN); }
    }

    public static void SetWinFullScreen(IntPtr hwnd)
    {
        SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
    }
}

答案 19 :(得分:1)

应该是这样的:

 function isJson($string)
 {
    // 1. Speed up the checking & prevent exception throw when non string is passed
    if (is_numeric($string) ||
        !is_string($string) ||
        !$string) {
        return false;
    }

    $cleaned_str = trim($string);
    if (!$cleaned_str || !in_array($cleaned_str[0], ['{', '['])) {
        return false;
    }

    // 2. Actual checking
    $str = json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE) && $str && $str != $string;
}

<强>单元测试

public function testIsJson()
{
    $non_json_values = [
        "12",
        0,
        1,
        12,
        -1,
        '',
        null,
        0.1,
        '.',
        "''",
        true,
        false,
        [],
        '""',
        '[]',
        '   {',
        '   [',
    ];

   $json_values = [
        '{}',
        '{"foo": "bar"}',
        '[{}]',
        '  {}',
        ' {}  '
    ];

   foreach ($non_json_values as $non_json_value) {
        $is_json = isJson($non_json_value);
        $this->assertFalse($is_json);
    }

    foreach ($json_values as $json_value) {
        $is_json = isJson($json_value);
        $this->assertTrue($is_json);
    }
}

答案 20 :(得分:1)

我不知道我的解决方案的性能或优雅,但它正是我正在使用的:

if (preg_match('/^[\[\{]\"/', $string)) {
    $aJson = json_decode($string, true);
    if (!is_null($aJson)) {
       ... do stuff here ...
    }
}

由于我所有的JSON编码字符串都以{“开头用RegEx来测试它。”我对RegEx不太熟悉,所以可能有更好的方法来执行此操作。另外:{{3}可能会更快。

试图让我的价值更高。

P.S。刚刚将RegEx字符串更新为/^[\[\{]\"/以查找JSON数组字符串。所以它现在在字符串的开头查找[“或{”。

答案 21 :(得分:1)

嗨,这是我库中的一小段代码,在这种情况下,我只是检查数据是否为json,如果正确解码则返回它,请注意性能的substr用法(我还没有看到任何json文件不以{或[

void Main()
{
    var files = new[] 
    {
        "Lightbox1.png",
        "Lightbox2.png",
        "Lightbox10.png",
        "Lightbox4.png",
        "Lightbox3.png",
        "Lightbox11.png",
        "Lightbox7.png",
    };

    foreach (var f in files.OrderBy(x=>getFileNumber(x)))
        Console.WriteLine(f);
}

int getFileNumber(string filename)
{
    var n = new String(filename.Where(x=>char.IsNumber(x)).ToArray());
    if (int.TryParse(n, out int i))
        return i;
    // parse failed
    return -1;

}

答案 22 :(得分:0)

function isJson($string) {
    $obj = json_decode($string);
    return json_last_error() === JSON_ERROR_NONE && gettype($obj ) == "object";
}

这有效并且不会为数字返回 true

答案 23 :(得分:0)

如果本地文件 stations.json 无效、丢失或超过一个月,请执行某些操作。

if (!is_array(json_decode(@file_get_contents("stations.json"))) || time() > filemtime("stations.json") + (60*60*24*31)){
  // The json file is invalid, missing, or is more than 1 month old
  // Get a fresh version
} else {
  // Up to date
}

答案 24 :(得分:0)

$r = (array)json_decode($arr);
if(!is_array($r) || count($r) < 1) return false;

答案 25 :(得分:0)

我的另一个建议:)

function isJson(string $string) {
  return ($result = json_decode($string, true)) ? $result : $string;
}

答案 26 :(得分:0)

PHP 5.2兼容性的新制作功能,如果您需要成功的解码数据:

function try_json_decode( $json, & $success = null ){
  // non-strings may cause warnings
  if( !is_string( $json )){
    $success = false;
    return $json;
  }

  $data = json_decode( $json );

  // output arg
  $success =

    // non-null data: success!
    $data !==  null  ||

    // null data from 'null' json: success!
    $json === 'null' ||

    // null data from '  null  ' json padded with whitespaces: success!
    preg_match('/^\s*null\s*$/', $json );

  // return decoded or original data
  return $success ? $data : $json;
}

用法:

$json_or_not = ...;

$data = try_json_decode( $json_or_not, $success );

if( $success )
     process_data( $data );
else what_the_hell_is_it( $data );

一些测试:

var_dump( try_json_decode( array(), $success ), $success );
// ret = array(0){}, $success == bool(false)

var_dump( try_json_decode( 123, $success ), $success );
// ret = int(123), $success == bool(false)

var_dump( try_json_decode('      ', $success ), $success );
// ret = string(6) "      ", $success == bool(false)

var_dump( try_json_decode( null, $success ), $success );
// ret = NULL, $success == bool(false)

var_dump( try_json_decode('null', $success ), $success );
// ret = NULL, $success == bool(true)

var_dump( try_json_decode('  null  ', $success ), $success );
// ret = NULL, $success == bool(true)

var_dump( try_json_decode('  true  ', $success ), $success );
// ret = bool(true), $success == bool(true)

var_dump( try_json_decode('  "hello"  ', $success ), $success );
// ret = string(5) "hello", $success == bool(true)

var_dump( try_json_decode('  {"a":123}  ', $success ), $success );
// ret = object(stdClass)#2 (1) { ["a"]=> int(123) }, $success == bool(true)

答案 27 :(得分:0)

可能将可能的JSON对象解码为PHP对象/数组的最快方法:

/**
 * If $value is a JSON encoded object or array it will be decoded 
 * and returned.
 * If $value is not JSON format, then it will be returned unmodified.
 */
function get_data( $value ) {
    if ( ! is_string( $value ) ) { return $value; }
    if ( strlen( $value ) < 2 ) { return $value; }
    if ( '{' != $value[0] && '[' != $value[0] ) { return $value; }

    $json_data = json_decode( $value );
    if ( ! $json_data ) { return $value; }
    return $json_data;
}

答案 28 :(得分:0)

简单修改henrik的答案,触及最需要的可能性。

(包括&#34; {}和[]&#34;)

function isValidJson($string) {
    json_decode($string);
    if(json_last_error() == JSON_ERROR_NONE) {

        if( $string[0] == "{" || $string[0] == "[" ) { 
            $first = $string [0];

            if( substr($string, -1) == "}" || substr($string, -1) == "]" ) {
                $last = substr($string, -1);

                if($first == "{" && $last == "}"){
                    return true;
                }

                if($first == "[" && $last == "]"){
                    return true;
                }

                return false;

            }
            return false;
        }

        return false;
    }

    return false;

}

答案 29 :(得分:0)

function is_json($input) {

    $input = trim($input);

    if (substr($input,0,1)!='{' OR substr($input,-1,1)!='}')
        return false;

    return is_array(@json_decode($input, true));
}

答案 30 :(得分:-1)

这是我的建议

if (!in_array(substr($string, 0, 1), ['{', '[']) || !in_array(substr($string, -1), ['}', ']'])) {
  return false;
} else {
  json_decode($string);
  return (json_last_error() === JSON_ERROR_NONE);
}