skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. Either store values in variables for reference before descending deeper into the structure:

    . as {$id} | .activities[] | .cities[] as $city
    | [$id, .time, $city, .type] | @tsv
    

    Demo

    Or add the final pieces together while iterating over the parts separately:

    [.id] + (.activities[] | [.time] + (.cities[] | [.]) + [.type]) | @tsv
    

    Demo

    Output:

    1   1659800397  london  1
    1   1659800397  paris   1
    1   1659800411  rome    2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search