1

I using JSONPath with PHP and i need the xpath equivalent to the contains filter, "contains(dept, 'Management')";

I have the following JSON and i want to filter the staff members to the Management Dept only. If the department node only contains 1 department then it's no problem, but i need find the keyword within department string?

Any help would be appreciated.

{ 
    "staff": {
        "members": [ 
            { 
            "firstname": "J",
                "lastname": "H",
                "department": "Management, Finance"
            },
            { 
                "firstname": "S",
                "lastname": "M",
                "department": "Finance"
            }
        ]
    }
}

$parser->setPath("$..members[?(@['department']=='Management')]");
$staff = $parser->getData();
var_dump($staff);
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
rossjha
  • 191
  • 3
  • 12

2 Answers2

2

Look at this

JSONPath :contains filter

I would assume in your case wil be something like.

"$..members[?(/Management/.test(@['department']))";
Community
  • 1
  • 1
Elijan
  • 1,406
  • 1
  • 8
  • 11
  • I tried "$..members[?(/Management/.(@['department']))", but not sure of the format, what would i replace .test with? Also is this javaScript specific? – rossjha Apr 22 '11 at 12:55
  • @rossjha yeah it was JavaScript specific. I donw what xpath.php parser for PHP are you you using, but see what expression they offer and if there is anything 'like' or as in example above where you can use regular expressions (test is a fucntion) – Elijan Apr 22 '11 at 13:40
  • Thanks Eliijan, in the examples found here:- http://jsonpath.googlecode.com/svn/trunk/tests/jsonpath-test-php.php there is examples of strpos being used and i can see in the jsonpath.php file there is an eval function, but again stuck with the syntax. Tried the following: "$..members.[?(@ && @[\'department\'] && strpos(@[\'department\'],\'Management\')!==false)]" but no joy. Using Michal Migurski's JSON parser as suggested so i'll take a look at this also. – rossjha Apr 22 '11 at 13:43
0

I managed to figure this out. There are examples found in http://jsonpath.googlecode.com/svn/trunk/tests/jsonpath-test-php.php which use PHP strpos, but this didn't work for me initially using jsonpath-0.8.1.php.

I gave jsonpath-0.8.3.php found the the repository and the strpos expression worked perfectly:-

$..members[?(@ && @['department'] && strpos(@['department'],'".$dept."')!==false)]

Note, the function evalx() has a third parameter which causes errors, setting the value to null works fine, see http://code.google.com/p/jsonpath/issues/detail?id=8

function evalx($x, $v, $vname=null)
rossjha
  • 191
  • 3
  • 12