Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Monarth Sarvaiya Avatar asked Sep 18 '25 04:09

Monarth Sarvaiya


1 Answers

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>
like image 176
Isha Padalia Avatar answered Sep 20 '25 18:09

Isha Padalia