JsonPath-PHP icon indicating copy to clipboard operation
JsonPath-PHP copied to clipboard

Remove without field

Open chrisvanpatten opened this issue 4 years ago • 2 comments

I did a bit of experimentation with a PR but wasn't quite able to get it to work, so I thought I'd take this to an issue to look for some ideas on how to implement :)

Given the sample document, I'm interested in being able to use remove() without providing a field, e.g. removing all matching paths.

Essentially supporting something like this:

$jsonObject = new JsonObject($json);

$jsonObject->remove("$..book[?(@.category == 'fiction')]");

$results = $jsonObject->toValue();

// $results with all fiction books removed.

I tried a simple unset($element); in the remove code but PHP's unset only unsets the reference, not the original value, so it doesn't quite work.

chrisvanpatten avatar May 13 '20 19:05 chrisvanpatten

Hi there! Sounds like a good addition.

Have you tried passing an optional parameter to getReal() stating the action, ie.remove, and have the remove logic happen when traversing the internal array? Instead of appending the match to $selection you could unset it from its parent.

Galbar avatar May 29 '20 08:05 Galbar

Hi ! Here some workarround

$exploded = explode(".",  $fieldName);
$field = array_pop($exploded);
$imploded = implode(".", $exploded);
$jsonPath = "$";
if (!empty($imploded)) {
    $jsonPath .= ".".$imploded;
}
$jsonPathObject->remove($jsonPath, $field);

It's works on simple cases like $.store.bicycle.price

fbruno93 avatar Aug 16 '23 10:08 fbruno93