PHP 查找错误的 JSON 元素


php find wrong json element

我有一个json形式的字符串,我将其解码为php变量。但是,如果 json 不是有效的 json 字符串,则解码会给出 NULL。

我正在寻找一个脚本,它可以告诉我解码将在哪个部分失败。

例如,我有以下字符串:

{ "error": "OK", "pathlist": [ { "path": "datu5" "pathId": "10100010" }, { "path": "datum", "pathId": "10100011" } ] }

然后我想表明该错误是第 4 行附近的错误:例如:

Error: Parse error on line 4: ... "path" : "datu5" "pathId" : "10100010 ----------------------^ Expecting 'EOF', '}', ':', ',', ']', got 'STRING'

我有这样的 php 脚本?

试试这个库:https://github.com/Seldaek/jsonlint

用法

use Seld'JsonLint'JsonParser;
$parser = new JsonParser();
// returns null if it's valid json, or a ParsingException object.
$parser->lint($json);
// Call getMessage() on the exception object to get
// a well formatted error message error like this
// Parse error on line 2:
// ... "key": "value"    "numbers": [1, 2, 3]
// ----------------------^
// Expected one of: 'EOF', '}', ':', ',', ']'
// Call getDetails() on the exception to get more info.
// returns parsed json, like json_decode() does, but slower, throws
// exceptions on failure.
$parser->parse($json);