Search code examples
javascriptjsonjmespath

How to check an array inside json data is empty using jmespath?


I have json data as below:

[
  {
    "id": "i_1",
    "name": "abc",
    "address": [
      {
        "city": [
          "city1",
          "city2"
        ]
      },
      {
        "city": [
          "city1",
          "city2"
        ]
      }
    ]
  },
  {
    "id": "i_2",
    "name": "def",
    "address": [
      {
        "city": []
      },
      {
        "city": []
      }
    ]
  }
]

Now, I want only that data where city array is not null. So in the above example the output should be 1st element i.e. with id i_1.

How to filter this json using jmespath library?


Solution

  • You can do this:

    var arr = [
      {
        "id": "i_1",
        "name": "abc",
        "address": [
          {
            "city": [
              "city1",
              "city2"
            ]
          },
          {
            "city": [
              "city1",
              "city2"
            ]
          }
        ]
      },
      {
        "id": "i_2",
        "name": "def",
        "address": [
          {
            "city": []
          },
          {
            "city": []
          }
        ]
      }
    ];
    
    console.log(jmespath.search(arr,"[?not_null(address[].city[])]"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.js"></script>