I'm trying to convert this JSON to CSV with some condition. And my condition is "type" should be "secondary". It should display the field having type secondary. Getting error with below cmd.
jq -r '["color","category","type"], ([?type=="secondary"].colors | [.color, .category, .type]) | @csv' test.json > test.csv
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,0,0,1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0,0,255,1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,0,1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "#0F0"
}
}
]
}
What you have appears to be a JSONPath syntax (https://github.com/json-path/JsonPath) , which is not applicable in jq
which has its own DSL syntax
For this specific case to filter on a condition, you need a select
statement
[ "color", "category", "type" ],
( .colors[] | select( .type == "secondary" ) | [ .color, .category, .type] ) | @csv