3

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?

Monarth Sarvaiya
  • 1,041
  • 8
  • 20

3 Answers3

4

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>
Isha Padalia
  • 877
  • 7
  • 24
0

You could do this in pure javascript using filter and every

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

const filtered = items.filter(i => i.address.every(a => a.city && a.city.length > 0))

console.log(filtered)

This returns only if every object inside address has a non-empty city array.

adiga
  • 34,372
  • 9
  • 61
  • 83
0

You don't need to use jmespath library use filter and `every from the vanilla JS. It is more efficient.

let jsonTxt = '{"data":[{"id":"i_1","name":"abc","address":[{"city":["city1","city2"]},{"city":["city1","city2"]}]},{"id":"i_2","name":"def","address":[{"city":[]},{"city":[]}]}]}'

let jsonData = JSON.parse(jsonTxt);
let items = jsonData.data;
const result = items.filter(i => i.address.every(a => a.city && a.city.length))
console.log('id: ', result[0].id);
//using jmespath
console.log(jmespath.search({data: items}, "data[*].address[*].city"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.js"></script>
Teocci
  • 7,189
  • 1
  • 50
  • 48
  • I am using other filters of jmespath, at this point I am stuck, so I want solution only using jmespath. Here is only some part of my code. – Monarth Sarvaiya Jan 28 '19 at 09:02