Galbar / JsonPath-PHP

A JsonPath implementation in PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Get parent by child

oliverbj opened this issue · comments

Hey!

First of all - great package! Thank you for porting this to PHP.

I am trying to select a parent node (nested), by querying a child node. Example:

{
    "NoteCollection":{
     "Note":{
        "Description":"Marks & Numbers",
        "IsCustomDescription":"false",
        "NoteText":"n\/m",
        "NoteContext":{
           "Code":"AAA",
           "Description":"Module: A - All, Direction: A - All, Freight: A - All"
        },
        "Visibility":{
           "Code":"PUB",
           "Description":"CLIENT-VISIBLE"
        }
     }
    }
}

I want to get all Note objects, where Visibility.Code == PUB.

I can do this using the below query:

$..NoteCollection.Note[?(@.Code == "PUB")]^

Note the ^ at the end. This takes the parent node. However, if I try to do this using JsonPath-PHP, I get the following error:

Error in JSONPath near '^'

How can I get the parent id, based on a child query?

This library does not implement the parent operator ^.

Instead you can do something like '$..NoteCollection[?(@.Visibility.Code == "PUB")]', which for your example above returns:

[
  {
    "Description": "Marks & Numbers",
    "IsCustomDescription": "false",
    "NoteText": "n/m",
    "NoteContext": {
      "Code": "AAA",
      "Description": "Module: A - All, Direction: A - All, Freight: A - All"
    },
    "Visibility": {
      "Code": "PUB",
      "Description": "CLIENT-VISIBLE"
    }
  }
]

Thank you - especially for a fast response! It worked :)

Can I ask you where you test the JSONPath? I use https://jsonpath.com/ - and the JSONPath you provided is invalid here (but works fine in my code).

I test my queries using the file app/test.php in the repository. It's usage is:
Usage: app/test.php <jsonpath> [<file to json>].

Also, in the README file you can find this implementation's language specification and examples demonstrating the features.

I don't generally use jsonpath.com to test as their implementation is slightly different than this one and implements operators not supported by this library. Nevertheless, I've tried the query above and it seems to work on that website:
image

Maybe you copied the quotes surrounding the query that I posted?