Search code examples
c#jsonjsonpathjson-query

Json Path querying without an array


In the below JSON I am trying to find a condition.Where I want the result only if OrderNumber is not empty or null.

Conditions I have tried. But havent worked for me are:

> $..Item[?(@.OrderNumber)]
> $..Item[?(@.CurrentOrder.OrderNumber)]

Any suggestions will be appreciated. I am testing my queries here https://jsonpath.curiousconcept.com/

{
        "Response": {
            "ID": "123456",
             "Items": {
                "Item": [
                    {                       
                        "CurrentOrder": {
                            "OrderNumber": "123",
                            "Status": ""
                        }
                    }
                ]
            }
        }
    }

Solution

  • $..Item[?(@.CurrentOrder.OrderNumber)] is the correct JSONPath for your case.

    The tool you used is known to not working correctly. See for example this question.

    I have test above query with JSONPath Online Evaluator and for JSON

    {
        "Response": {
            "ID": "123456",
            "Items": {
                "Item": [
                    {
                        "CurrentOrder": {
                            "OrderNumber": "123",
                            "Status": ""
                        }
                    },
                    {
                        "CurrentOrder": {
                            "OrderNumber": "456",
                            "Status": ""
                        }
                    },
                    {
                        "CurrentOrder": {
                            "Status": ""
                        }
                    }
                ]
            }
        }
    }
    

    it gives correct result:

    [
      {
        "CurrentOrder": {
          "OrderNumber": "123",
          "Status": ""
        }
      },
      {
        "CurrentOrder": {
          "OrderNumber": "456",
          "Status": ""
        }
      }
    ]