I have the following json object:
{
"id":1,
"activities":[
{"time":1659800397,"cities":["london","paris"],"type":1},
{"time":1659800411,"cities":["rome"], "type":2}
]
}
I would like to flatten it to the following tab separated structure, perhaps using jq
id | time | cities | type |
---|---|---|---|
1 | 1659800397 | london | 1 |
1 | 1659800397 | paris | 1 |
1 | 1659800411 | rome | 2 |
2
Answers
I found out myself the solution, that however I think could be useful also to others.
jq -r '.id as $id | .activities[] | "($id);(.time);(.type);(.cities[])"' input.json
Here's how the code works:
'.id as $id' extracts the "id" field and assigns it to the variable $id. '.activities[]' iterates over each object in the "activities" array. '"...($id);(.time);(.type);(.cities[])"' constructs the desired output format with the extracted values, using the variables and fields we defined.
Either store values in variables for reference before descending deeper into the structure:
Demo
Or add the final pieces together while iterating over the parts separately:
Demo
Output: