Reputation: 61
Given this input
{
"data": [
{
"id": "001",
"metadata": {
"item1": 1
},
"records": [
{
"name": "name1",
"type": "type1"
},
{
"name": "name2",
"type": "type2"
}
]
},
{
"id": "002",
"metadata": {
"item1": 1
},
"records": [
{
"name": "name1",
"type": "type1"
}
]
},
{
"id": "003",
"metadata": {},
"records": [
{
"name": "name1",
"type": "type1"
},
{
"name": "name2",
"type": "type2"
}
]
}
]
}
I am trying to output this
[
{
"id": "001",
"Item1": 1,
"Name": "name2"
},
{
"id": "002",
"Item1": 1,
"Name": null
},
{
"id": "003",
"Item1": null,
"Name": "name2"
}
]
However using this
jq '[.data[] | {id, "Item1": .metadata.item1, "Name": .records[] | select(.type == "type2").name}]'
jq query I am getting this
[
{
"id": "001",
"Item1": 1,
"Name": "name2"
},
{
"id": "003",
"Item1": null,
"Name": "name2"
}
]
How can I get the '002' id object to output as well? I have tried various if then else conditions statements but to no avail.
Upvotes: 0
Views: 381
Reputation: 47099
I am quite new to jq
so this is probably not an optimal solution.
If you map
the select
onto the records array instead, the surrounding object is not removed. For example:
parse.jq
[
.data[] |
{
id : .id,
Item1 : .metadata.item1,
Name : .records | map(select(.type == "type2"))[0].name
}
]
Run it like this:
jq -f parse.jq file.json
Output:
[
{
"id": "001",
"Item1": 1,
"Name": "type2"
},
{
"id": "002",
"Item1": 1,
"Name": null
},
{
"id": "003",
"Item1": null,
"Name": "type2"
}
]
Upvotes: 1
Reputation: 2639
It can be because the 2nd nested array doesn't satisfy the condition
select(.type == "type2")
Upvotes: 0