Search code examples
jsonpath

JSONPath impossible to create a sort correctly


I begin with Json Path and I'm stuck.

I would like have a list of the "names" of all persons who have "Registered" enter in "group_names".

I try this path :

$.data.attributes[?(@.group_names=='Registered')].name

but my result is null.

Here my full api response :

{
  "links": {
    "self": "/api/index.php/v1/users"
  },
  "data": [
    {
      "type": "users",
      "id": "977",
      "attributes": {
        "id": 977,
        "name": "Bryan",
        "username": "Bryan",
        "block": 0,
        "sendEmail": 0,
        "registerDate": "2023-08-21 12:16:14",
        "lastvisitDate": "2023-08-21 12:22:15",
        "lastResetTime": null,
        "resetCount": 0,
        "group_count": 1,
        "group_names": "Registered"
      }
    },
{
      "type": "users",
      "id": "971",
      "attributes": {
        "id": 971,
        "name": "easy",
        "username": "easy",
        "block": 0,
        "sendEmail": 0,
        "registerDate": "2023-08-16 11:32:03",
        "lastvisitDate": "2023-08-21 10:48:12",
        "lastResetTime": null,
        "resetCount": 0,
        "group_count": 2,
        "group_names": "Registered\nSuper Users"
      }
    },
    {
      "type": "users",
      "id": "968",
      "attributes": {
        "id": 968,
        "name": "Machin",
        "username": "Machin",
        "block": 0,
        "sendEmail": 0,
        "registerDate": "2023-06-17 18:08:31",
        "lastvisitDate": "2023-08-25 07:46:04",
        "lastResetTime": null,
        "resetCount": 0,
        "group_count": 1,
        "group_names": "Registered"
      }
    },
    ]

I supposed is a newbee question but if someone can help me :-)

Thanks a lot !

I can out a lit of names but not with a sorting :-/


Solution

  • To get the "names" of all persons who have "Registered" enter in "group_names":

    $.data[?(@.attributes.group_names == "Registered")].attributes.name
    

    This expression will filter the "data" array based on the condition that the "group_names" field is equal to "Registered" and then extract the corresponding "name" field.
    Applying this JSON Path expression to API response, the list of names would be:

    • Bryan
    • Machin