I want to convert json to csv.
I use tool "jq" for this
Here json
{
"total": 2040,
"created_at": "2022-01-27T09:50:59 0200",
"project": "my project",
"issues": [
{
"key": "1",
"component": "my_component",
"textRange": {
"startLine": 35,
"endLine": 35,
"startOffset": 46,
"endOffset": 84
},
"flows": [],
"status": "OPEN",
"creationDate": "2022-01-24T06:42:58 0200",
"updateDate": "2022-01-24T06:42:58 0200",
"type": "BUG",
"scope": "MAIN"
},
{
"key": "2",
"component": "my component 2",
"textRange": {
"startLine": 34,
"endLine": 34,
"startOffset": 3,
"endOffset": 52
},
"flows": [
{
"locations": [
{
"component": "some component",
"textRange": {
"startLine": 35,
"endLine": 35,
"startOffset": 3,
"endOffset": 50
},
"msg": "Code"
}
]
},
{
"locations": [
{
"component": "another component",
"textRange": {
"startLine": 36,
"endLine": 36,
"startOffset": 3,
"endOffset": 71
},
"msg": "Code"
}
]
},
{
"locations": [
{
"component": "Alarm.java",
"textRange": {
"startLine": 37,
"endLine": 37,
"startOffset": 3,
"endOffset": 76
},
"msg": "Code"
}
]
},
{
"locations": [
{
"component": "Alarm.java",
"textRange": {
"startLine": 38,
"endLine": 38,
"startOffset": 3,
"endOffset": 50
},
"msg": "Code"
}
]
}
]
}
]
}
And here convert to csv only some flelds:
jq -r '.issues[] | [.key ,.component, .textRange[], .status] | @csv' test.json
And here result:
"1","my_component",35,35,46,84,"OPEN"
"2","my component 2",34,34,3,52,
Nice.
Now I want to convert field (array) flows. I try this:
jq -r '.issues[] | [.key ,.component, .textRange[], .flows[], .status] | @csv' test.json
And here result:
"1","my_component",35,35,46,84,"OPEN"
jq: error (at test.json:91): object ({"locations...) is not valid in a csv row
How fix convert? Array (locations) in array (flows)
CodePudding user response:
Do you want the objects in .flows[].loacations[] to be appended as separate rows?
jq -r '.issues[]
| .key as $key | ., .flows[].locations[]
| [$key ,.component, .textRange[], .status]
| @csv
'
"1","my_component",35,35,46,84,"OPEN"
"2","my component 2",34,34,3,52,
"2","some component",35,35,3,50,
"2","another component",36,36,3,71,
"2","Alarm.java",37,37,3,76,
"2","Alarm.java",38,38,3,50,
CodePudding user response:
Seems you need stringify, then you can use tostring such as
jq -r '.issues[] | [.key ,.component, .textRange[], (.flows[].locations[]|tostring), .status] | @csv'
