使用 php jsonpath 解析 JSON

2024-02-11

我正在尝试使用 jsonpath 解析 PHP 中的 JSON ....

我的 JSON 来自于此

https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs

(此处剪切/粘贴太长,但您可以在浏览器会话中看到它......)

JSON 是一个有效的 JSON(我已经使用它进行了验证)https://jsonlint.com/ https://jsonlint.com/ ... ).

我尝试过使用 jsonpath 表达式http://www.jsonquerytool.com/ http://www.jsonquerytool.com/一切似乎都工作正常,但是当我将所有内容放入下面的 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.";
   } 
?>

...没有打印任何值..只有“假”值。

当我将 jsonpath 表达式放入 PHP 代码中时,它出现问题:出现的错误如下

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

也许我必须转义/引用我的 jsonpath 才能在 PHP 中使用它,但我不知道如何...任何建议表示赞赏...

注意:我需要使用 jsonpath 表达式,例如?(@.descrizione=="A.S.U.I. - Trieste")我不能使用“位置”json 路径...

我还尝试使用来自这里的 jsonpath-0.8.3.phphttps://github.com/ITS-UofIowa/jsonpath/blob/master/jsonpath.php https://github.com/ITS-UofIowa/jsonpath/blob/master/jsonpath.php,但没有任何改变...

建议?

先感谢您 ...


您可以使用 json_decode 将其转换为本机 php 数组,然后您可以使用 hhb_xml_encode (来自https://stackoverflow.com/a/43697765/1067003 https://stackoverflow.com/a/43697765/1067003)将数组转换为 xml,然后您可以使用 DOMDocument::loadHTML 将 XML 转换为 DOMDocument,然后您可以使用 DOMXPath::query 通过 XPaths 搜索它...

example:

<?php
declare(strict_types = 1);
header ( "content-type: text/plain;charset=utf8" );
require_once ('hhb_.inc.php');
$json_raw = (new hhb_curl ( '', true ))->exec ( 'https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs' )->getStdOut ();
$parsed = json_decode ( $json_raw, true );
// var_dump ( $parsed );
$xml = hhb_xml_encode ( $parsed );
// var_dump($xml);
$dom = @DOMDocument::loadHTML ( $xml );
$dom->formatOutput = true;
$xp = new DOMXPath ( $dom );
$elements_for_parsing = $xp->query ( '//aziende/descrizione[text()=' . xpath_quote ( 'A.S.U.I. - Trieste' ) . ']|//prontosoccorsi/descrizione[text()=' . xpath_quote ( 'Pronto Soccorso e Terapia Urgenza Trieste' ) . ']|//dipartimenti/descrizione[text()=' . xpath_quote ( 'Pronto Soccorso Maggiore' ) . ']|//codicicolore/descrizione[text()=' . xpath_quote ( 'Bianco' ) . ']|//situazionepazienti|//numeroPazientiInAttesa' );
// var_dump ( $elements_for_parsing,$dom->saveXML() );
foreach ( $elements_for_parsing as $ele ) {
    var_dump ( $ele->textContent );
}

// based on https://stackoverflow.com/a/1352556/1067003
function xpath_quote(string $value): string {
    if (false === strpos ( $value, '"' )) {
        return '"' . $value . '"';
    }
    if (false === strpos ( $value, '\'' )) {
        return '\'' . $value . '\'';
    }
    // if the value contains both single and double quotes, construct an
    // expression that concatenates all non-double-quote substrings with
    // the quotes, e.g.:
    //
    // concat("'foo'", '"', "bar")
    $sb = 'concat(';
    $substrings = explode ( '"', $value );
    for($i = 0; $i < count ( $substrings ); ++ $i) {
        $needComma = ($i > 0);
        if ($substrings [$i] !== '') {
            if ($i > 0) {
                $sb .= ', ';
            }
            $sb .= '"' . $substrings [$i] . '"';
            $needComma = true;
        }
        if ($i < (count ( $substrings ) - 1)) {
            if ($needComma) {
                $sb .= ', ';
            }
            $sb .= "'\"'";
        }
    }
    $sb .= ')';
    return $sb;
}
function hhb_xml_encode(array $arr, string $name_for_numeric_keys = 'val'): string {
    if (empty ( $arr )) {
        // avoid having a special case for <root/> and <root></root> i guess
        return '';
    }
    $is_iterable_compat = function ($v): bool {
        // php 7.0 compat for php7.1+'s is_itrable
        return is_array ( $v ) || ($v instanceof \Traversable);
    };
    $isAssoc = function (array $arr): bool {
        // thanks to Mark Amery for this
        if (array () === $arr)
            return false;
        return array_keys ( $arr ) !== range ( 0, count ( $arr ) - 1 );
    };
    $endsWith = function (string $haystack, string $needle): bool {
        // thanks to MrHus
        $length = strlen ( $needle );
        if ($length == 0) {
            return true;
        }
        return (substr ( $haystack, - $length ) === $needle);
    };
    $formatXML = function (string $xml) use ($endsWith): string {
        // there seems to be a bug with formatOutput on DOMDocuments that have used importNode with $deep=true
        // on PHP 7.0.15...
        $domd = new DOMDocument ( '1.0', 'UTF-8' );
        $domd->preserveWhiteSpace = false;
        $domd->formatOutput = true;
        $domd->loadXML ( '<root>' . $xml . '</root>' );
        $ret = trim ( $domd->saveXML ( $domd->getElementsByTagName ( "root" )->item ( 0 ) ) );
        assert ( 0 === strpos ( $ret, '<root>' ) );
        assert ( $endsWith ( $ret, '</root>' ) );
        $full = trim ( substr ( $ret, strlen ( '<root>' ), - strlen ( '</root>' ) ) );
        $ret = '';
        // ... seems each line except the first line starts with 2 ugly spaces,
        // presumably its the <root> element that starts with no spaces at all.
        foreach ( explode ( "\n", $full ) as $line ) {
            if (substr ( $line, 0, 2 ) === '  ') {
                $ret .= substr ( $line, 2 ) . "\n";
            } else {
                $ret .= $line . "\n";
            }
        }
        $ret = trim ( $ret );
        return $ret;
    };

    // $arr = new RecursiveArrayIterator ( $arr );
    // $iterator = new RecursiveIteratorIterator ( $arr, RecursiveIteratorIterator::SELF_FIRST );
    $iterator = $arr;
    $domd = new DOMDocument ();
    $root = $domd->createElement ( 'root' );
    foreach ( $iterator as $key => $val ) {
        // var_dump ( $key, $val );
        $ele = $domd->createElement ( is_int ( $key ) ? $name_for_numeric_keys : $key );
        if (! empty ( $val ) || $val === '0') {
            if ($is_iterable_compat ( $val )) {
                $asoc = $isAssoc ( $val );
                $tmp = hhb_xml_encode ( $val, is_int ( $key ) ? $name_for_numeric_keys : $key );
                // var_dump ( $tmp );
                // die ();
                $tmp = @DOMDocument::loadXML ( '<root>' . $tmp . '</root>' );
                foreach ( $tmp->getElementsByTagName ( "root" )->item ( 0 )->childNodes ?? [ ] as $tmp2 ) {
                    $tmp3 = $domd->importNode ( $tmp2, true );
                    if ($asoc) {
                        $ele->appendChild ( $tmp3 );
                    } else {
                        $root->appendChild ( $tmp3 );
                    }
                }
                unset ( $tmp, $tmp2, $tmp3 );
                if (! $asoc) {
                    // echo 'REMOVING';die();
                    // $ele->parentNode->removeChild($ele);
                    continue;
                }
            } else {
                $ele->textContent = $val;
            }
        }
        $root->appendChild ( $ele );
    }
    $domd->preserveWhiteSpace = false;
    $domd->formatOutput = true;
    $ret = trim ( $domd->saveXML ( $root ) );
    assert ( 0 === strpos ( $ret, '<root>' ) );
    assert ( $endsWith ( $ret, '</root>' ) );
    $ret = trim ( substr ( $ret, strlen ( '<root>' ), - strlen ( '</root>' ) ) );
    // seems to be a bug with formatOutput on DOMDocuments that have used importNode with $deep=true..
    $ret = $formatXML ( $ret );
    return $ret;
}

ps,线条require_once ('hhb_.inc.php'); $json_raw = (new hhb_curl ( '', true ))->exec ( 'https://servizionline.sanita.fvg.it/tempiAttesaService/tempiAttesaPs' )->getStdOut ();只是获取 url 并将 json 放入 $json_raw (使用 gzip 压缩传输来加快速度),将其替换为您想要将其获取到 $json_raw 中的任何内容,我使用的实际curl库来自https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php#L477 https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php#L477

目前它打印:

string(18) "A.S.U.I. - Trieste"
string(41) "Pronto Soccorso e Terapia Urgenza Trieste"
string(9) "121200:14"
string(10) "181400:254"
string(6) "Bianco"
string(7) "200:292"
string(5) "00:00"
string(24) "Pronto Soccorso Maggiore"
string(7) "3300:15"
string(6) "Bianco"
string(8) "6200:584"
string(5) "00:00"
string(5) "00:00"
string(8) "4100:353"
string(6) "Bianco"
string(7) "100:051"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:15"
string(8) "6402:012"
string(6) "Bianco"
string(7) "402:274"
string(5) "00:00"
string(9) "11900:202"
string(9) "11401:427"
string(6) "Bianco"
string(8) "2102:051"
string(5) "00:00"
string(7) "3300:08"
string(8) "7401:423"
string(6) "Bianco"
string(8) "8402:104"
string(5) "00:00"
string(6) "Bianco"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:04"
string(10) "121000:512"
string(6) "Bianco"
string(8) "5400:461"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(6) "Bianco"
string(5) "00:00"
string(5) "00:00"
string(9) "121200:18"
string(9) "11800:593"
string(6) "Bianco"
string(8) "6401:272"
string(5) "00:00"
string(6) "Bianco"
string(7) "1100:04"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(7) "2200:05"
string(9) "10801:102"
string(6) "Bianco"
string(8) "8201:166"
string(5) "00:00"
string(8) "3200:071"
string(7) "100:261"
string(6) "Bianco"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:00"
string(9) "151500:26"
string(10) "161301:123"
string(6) "Bianco"
string(8) "9500:434"
string(7) "1100:00"
string(7) "2200:13"
string(6) "Bianco"
string(7) "200:342"
string(5) "00:00"
string(6) "Bianco"
string(7) "1100:24"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:04"
string(8) "9700:222"
string(10) "171500:582"
string(6) "Bianco"
string(7) "200:512"
string(7) "1100:40"
string(7) "1100:22"
string(6) "Bianco"
string(8) "3100:062"
string(5) "00:00"
string(5) "00:00"
string(5) "00:00"
string(6) "Bianco"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:22"
string(8) "7500:302"
string(6) "Bianco"
string(5) "00:00"
string(5) "00:00"
string(7) "1100:06"
string(6) "Bianco"
string(7) "1100:00"
string(5) "00:00"
string(5) "00:00"

希望这就是您正在寻找的东西,我是通过您提供的“xpath”猜测的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 php jsonpath 解析 JSON 的相关文章

  • 从 PHP 中的平面路径数组构建目录树

    所以 标题可能令人困惑 但我不知道如何表达这种数组结构 它肯定是一个树结构 但至于它的创建 这正是我所渴望的 它似乎不遵循典型的递归数组树构建 我正在尝试从平面路径数组创建列目录布局 每个路径都位于其自己的多维数组内 该数组旨在构建 mac
  • php 错误地将字符串中的 ¬ 转换为 Ø

    我需要在 PHP 中组成一个简单的字符串 它是要发布到另一个站点的数据字符串 问题是其中一个字段是 notify url 当我使用该字段时 PHP 将其前面的 和 not 部分表示逻辑运算符 AND NOT 并将其转换为 字符 string
  • 从 Yii 中的 registerScript 方法强制执行脚本顺序

    我创建了一个小部件 它注册了自己的脚本 如下所示 class MyWidget extends CWidget public function run Yii app gt clientScript gt registerScript CL
  • PHP:会话.auto_start

    我在同一台服务器上有两个项目 它们的设置在 session auto start 中冲突 相关post https stackoverflow com questions 1378324 php setting variables in i
  • 使用 PHPUnit 模拟对象是否有可能期望调用神奇的 __call() 方法?

    我在测试中有一个模拟对象 真实的对象 PageRepository 使用 call 实现了一个神奇的方法 因此如果您调用 pageRepository gt findOneByXXXX value of field XXXX 它将在数据库中
  • 奇怪的 500 内部服务器错误(firebug、php、display_errors、ajax)

    在一页上我正在进行多个 AJAX 调用 所有调用均成功返回响应 但最后一个调用 与其他 ajax 调用无关 返回 500 内部服务器错误作为响应代码 如 firebug 所示 但是 尽管存在错误代码 该 AJAX 调用仍会返回正确的内容 令
  • 服务容器的使用寿命是多少?

    我正在尝试了解 Symfony2 框架 来自 Java Spring 背景 我意识到 Symfony2 中的 Scope 与 Spring 中的 Scope 不同 此外 通过 Symfony3 范围已弃用 https stackoverfl
  • PHP 资产管道/框架

    背景 我正在致力于 现代化 一个现有的 PHP 驱动的网站 该网站最初是一个带有一些 php 方法的静态网站 它现在有一个移动网络应用程序 多个模型和大量动态内容 然而 随着时间的推移 应用程序本身的结构与它主要是静态站点时相比并没有太大变
  • 生成基于内联 HTML 样式的样式表?

    一段时间以来 我一直致力于对网站的不同部分进行样式设计 但是我尚未将内联样式放入样式表中 我想知道是否存在一个工具可以解析 HTML 文件并从中生成样式表 例如 这是我网站的一个片段 div class block style border
  • 如何从 PHP 访问表单的“名称”变量

    我正在尝试创建一个 BMI 计算器 这应该允许人们使用公制或英制测量单位 我意识到我可以使用隐藏标签来解决我的问题 但这之前曾困扰过我 所以我想我会问 我可以使用 POST variableName 查找提交的变量名字段值 但是 我不知道或
  • 从数值中获取颜色值

    我需要一个项目从值中获取颜色 我解释说 我有日期 每个数据必须用颜色表示 红色代表最大值 蓝色代表最小值 绿色代表中间值 一种热图 所以 我需要一个返回正确颜色的函数 我尝试过这样的事情 function datatocolor min m
  • 使用架构定义验证 JSON 对象

    只要我们可以根据预定义的模式 即 XSD 或 DTD 验证传入的 XML 文件 我们就可以对传入的 JSON 对象执行验证 有可用的 JSON 架构定义吗 有一个工作草案JSON 模式 http json schema org 您还可以看一
  • 访问php数组内部[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 我有一个像这样的数组打印 array 2 systems gt array 5 1 gt string 1 1111 2
  • Wordpress 编辑器中的“application/gas-events-abn”对象是什么?

    我正在使用 Wordpress 创建博客 我注意到当我多次保存帖子时 代码中会出现一个奇怪的元素 在帖子底部创建一个大的空白区域 代码如下所示 post content nbsp 每次我编辑帖子时 我都必须将其删除 Joomla 有时也会发
  • 没有字符串参数构造函数/工厂方法可以从字符串值 ('') 反序列化

    我在使用时遇到了 json 解析问题ObjectMapper类来自com fasterxml jackson databind包 我得到的错误是 com fasterxml jackson databind JsonMappingExcep
  • Node.js 中的 JSON Zip 响应

    我对 node js 还很陌生 我正在尝试发回包含 JSON 结果的 zip 文件 我一直在尝试弄清楚如何去做 但还没有达到预期的结果 我正在使用 NodeJS ExpressJS LocomotiveJS Mongoose 和 Mongo
  • DateTime.ParseExact - 为什么 yy 变成 2015 而不是 1915

    为什么 NET 假定以下年份是 2015 年 而不是 1915 年 var d DateTime ParseExact 20 11 15 dd MM yy new CultureInfo en GB 我想 它会尝试接近 但其背后是否有合理的
  • 在 Laravel Schema 中创建价格列

    我想在 Laravel 模式中创建一个价格列 public function up Schema create cameras function Blueprint table table gt increments id table gt
  • 如何使用 symfony 对管理面板中自己的列进行排序?

    M schema yml News columns title type string 50 category id type integer 4 relations Category local category id foreign c
  • Windows Phone 的 JSON 反序列化

    我正在尝试反序列化以下 JSON 但我真的不知道如何使用 JSON net 来完成这项工作 我正在使用 C 和 JSON Net 库 我的 JSON 如下 found 3 bounds 43 54919 172 62148 43 54487

随机推荐