如何使用 jmespath 检查 json 数据内的数组是否为空?

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

我有 json 数据如下:

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

现在,我只想要 city 数组不是 null 的数据。所以在上面的例子中,输出应该是第一个元素,即 id i_1.

如何使用 jmespath 库过滤此 json

您可以使用 filter and every

在纯 javascript 中执行此操作

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)

仅当 address 中的 每个 对象都有一个非空城市数组时,此 returns。

您不需要使用 jmespath 库 使用 filter 和 `every from the vanilla JS。效率更高

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>

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({ c: arr}, "not_null(c[].address[].city[])"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.js"></script>

我不知道你的结果是什么。你能解释得更好吗?

你可以这样做:

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>