Ces*_*are 8 php parsing json jsonpath
我正在尝试使用jsonpath解析PHP中的JSON ....
我的JSON来自于此
https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs
(这里剪切/粘贴太长了,但你可以在浏览器会话中看到它......)
JSON是一个有效的JSON(我已经使用https://jsonlint.com/ ... 验证了它).
我已经尝试使用http://www.jsonquerytool.com/的jsonpath表达式,所有看起来都很好,但是当我把所有的PHP代码示例放在下面....
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once('json.php'); // JSON parser
require_once('jsonpath-0.8.0.php'); // JSONPath evaluator
$url = 'https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs';
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_PROXY, '');
$data = curl_exec($ch);
curl_close($ch);
$parser = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$o = $parser->decode($data);
$xpath_for_parsing = '$..aziende[?(@.descrizione=="A.S.U.I. - Trieste")]..prontoSoccorsi[?(@.descrizione=="Pronto Soccorso e Terapia Urgenza Trieste")]..dipartimenti[?(@.descrizione=="Pronto Soccorso Maggiore")]..codiciColore[?(@.descrizione=="Bianco")]..situazionePazienti..numeroPazientiInAttesa';
$match1 = jsonPath($o, $xpath_for_parsing);
//print_r($match1);
$match1_encoded = $parser->encode($match1);
print_r($match1_encoded);
$match1_decoded = json_decode($match1_encoded);
//print_r($match1_decoded);
if ($match1_decoded[0] != '') {
return $match1_decoded[0];
}
else {
return "N.D.";
}
?>
Run Code Online (Sandbox Code Playgroud)
...没有打印任何值...只是一个"假"值.
当我把它放在我的PHP代码中时,我的jsonpath表达式出了问题:出现的错误如下
Warning: Missing argument 3 for JsonPath::evalx(), called in /var/www/html/OpenProntoSoccorso/Test/jsonpath-0.8.0.php on line 84 and defined in /var/www/html/OpenProntoSoccorso/Test/jsonpath-0.8.0.php on line 101
Notice: Use of undefined constant descrizione - assumed 'descrizione' in /var/www/html/OpenProntoSoccorso/Test/jsonpath-0.8.0.php(104) : eval()'d code on line 1
Run Code Online (Sandbox Code Playgroud)
可能我要逃避/引用我的jsonpath在PHP中使用它但我不知道如何......任何建议都值得赞赏...
注意:我需要使用jsonpath表达式?(@.descrizione=="A.S.U.I. - Trieste"),我不能使用"位置"json路径...
我也试过使用jsonpath-0.8.3.php来自这里https://github.com/ITS-UofIowa/jsonpath/blob/master/jsonpath.php,但没有任何变化......
建议?
先感谢您 ...
xpath 对于你的任务来说太复杂了并且一般来说太过分了......
只需使用标准json_decode(),获取等效的 PHP 对象并使用标准 for/while 循环和正则表达式对其进行导航
另外我认为你的问题具有误导性,你的问题不是解析 JSON (这是json_decode()自动完成的),你的问题是使用 xpath 从中提取一些数据。我建议重构你的问题,准确显示出了什么问题以及发生了什么你的意图
如果您需要深入到精确的 JSON 节点(或节点集),为什么不通过 for 循环和正则表达式来实现呢?