I need to create a csv report from a JSON file of the following structure (simplified as much as I saw fit):
{
"data": [
{
"id": "123",
"foo": {
"item": {
"value": "foo_good",
"bar_id": "1"
}
},
"bar": {
"item": {
"id": "1",
"value": "bar_value_1a"
}
},
"var": {
"item": {
"value": "var_value_1a",
"bar_id": "1"
}
}
},
{
"id": "456",
"foo": {
"item": [
{
"value": "foo_bad",
"bar_id": "1"
},
{
"value": "foo_good",
"bar_id": "2"
},
{
"value": "foo_good",
"bar_id": "2"
},
{
"value": "foo_bad",
"bar_id": "3"
},
{
"value": "foo_good",
"bar_id": "4"
}
]
},
"bar": {
"item": [
{
"id": "1",
"value": "bar_value_2a"
},
{
"id": "2",
"value": "bar_value_2b"
},
{
"id": "3",
"value": "bar_value_2c"
},
{
"id": "4",
"value": "bar_value_2d"
}
]
},
"var": {
"item": [
{
"value": "var_value_2a",
"bar_id": "1"
},
{
"value": "var_value_2b",
"bar_id": "2"
},
{
"value": "var_value_2c",
"bar_id": "3"
},
{
"value": "var_value_2d",
"bar_id": "4"
}
]
}
}
]
}
Data structure:
foo.itemandvar.itemare connected tobar.itemwithbar_id- One or more
foo.itempoint to onebar.item - Multiple
foo.itempointing to the samebar.itemwill have the samefoo.item.value - Exactly one
var.itempoints to onebar.item - All items are sorted by
bar_id - The format is inconsistent.
bar.itemis an object if there is only one item, it's an array otherwise (applies tofoo.itemandvar.itemas well) - I am stuck with this format
Output report:
- Process all
dataobjects - Create report for each
bar.itemthat does not have any correspondingfoo.itemwith a valuefoo_bad - The output format:
.id, .bar.item.value, .var.item.value
My attempt:
The temporary jq script I am currently using discards multiple bar.item etc. and creates mere estimation of the real data:
.data[]
| .foo.item |= if type=="array" then .[0] else . end
| .bar.item |= if type=="array" then .[0] else . end
| .var.item |= if type=="array" then .[0] else . end
| select(.foo.item.value != "foo_bad")
| [.id,.bar.item.value,.var.item.value]
| @csv
Which outputs the following:
"123","bar_value_1a","var_value_1a"
Desired output:
"123","bar_value_1a","var_value_1a"
"456","bar_value_2b","var_value_2b"
"456","bar_value_2d","var_value_2d"
I prefer using jq although I do not insist on it.