admin管理员组文章数量:1400117
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?
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?
3 Answers
Reset to default 5You 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./ajax/libs/jmespath/0.15.0/jmespath.js"></script>
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.
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./ajax/libs/jmespath/0.15.0/jmespath.js"></script>
本文标签: javascriptHow to check an array inside json data is empty using jmespathStack Overflow
版权声明:本文标题:javascript - How to check an array inside json data is empty using jmespath? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744247126a2597072.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论