如何在PHP中验证JSON?

25 php json well-formed

有没有办法在不使用PHP的情况下检查变量是否是有效的JSON字符串json_last_error()?我没有PHP 5.3.3.

Jef*_*ert 54

$ob = json_decode($json);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这不是真正的验证.仍然可以发送无效的json,但``json_decode()`会解释它,但不会按照你期望的方式解释它.这被认为是有效的json:`{"request":{"filterBy":"MCC""startDate":"Sun,02 Sep 2012 12:51:44 -0400","endDate":"Tue,02 Oct 2012 00 :00:00-0400"}}`即使在"MCC"之后缺少逗号 (15认同)
  • @Webnet在http://jsonlint.com上测试过,你的字符串没有验证.你能指出一个说你的字符串有效的规范或工具吗? (2认同)

Mar*_*c B 10

$data = json_decode($json_string);
if (is_null($data)) {
   die("Something dun gone blowed up!");
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*ima 9

If you want to check if your input is valid JSON, you might as well be interested in validating whether or not it follows a specific format, i.e a schema. In this case you can define your schema using JSON Schema and validate it using this library.

Example:

person.json

{
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}
Run Code Online (Sandbox Code Playgroud)

Validation

<?php

$data = '{"firstName":"Hermeto","lastName":"Pascoal"}';

$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('person.json')]);

$validator->isValid()
Run Code Online (Sandbox Code Playgroud)